gpt4 book ai didi

mysql - 如果值不为空,则为 DATEDIFF

转载 作者:行者123 更新时间:2023-11-29 07:25:35 26 4
gpt4 key购买 nike

这是此 question 的后续内容我之前发布过。

我正在使用以下语法计算 DATEDIFF 的 SUM

SUM(DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from)) / COUNT(DISTINCT e.company_id)

我现在想要的是计算SUMDATEDIFF仅当 e.time_period_from is NOT NULL

我尝试了以下查询。

SUM(IF(e.time_period_from IS NOT NULL), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(DISTINCT e.company_id)

这给了我 SQL 语法错误。

如何去做?

更新:

这是我完整的 MySQL 查询

SELECT
SQL_CALC_FOUND_ROWS
u.id,
u.name,
u.email,
COUNT(DISTINCT(question_id)) as number_of_answered_questions,
(SELECT option_id FROM answer WHERE user_id = u.id GROUP BY option_id ORDER BY COUNT(option_id) DESC LIMIT 1) as option_id,
SUM(IF(e.time_period_from IS NOT NULL), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(DISTINCT e.company_id) AS tenure_in_days
FROM
user u
LEFT JOIN
role r ON (r.id = u.role_id)
LEFT JOIN
answer a ON (a.user_id = u.id)
LEFT JOIN
employment e ON (e.user_id = u.id)
WHERE
r.slug = 'app_user'
GROUP BY
u.id
LIMIT
0, 10

如您所见,这是针对子选择的,我无法在其之外放置 where 条件。

这是我得到的错误。

"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '), DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0) / COUNT(D' at line 1"

谢谢。

最佳答案

就像我之前的评论一样,我认为你只是把括号设置错误了,你想要得到的是这样的:

SUM(IF(e.time_period_from IS NOT NULL, DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0))
/ COUNT(DISTINCT e.company_id)

关于mysql - 如果值不为空,则为 DATEDIFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34673015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com