DATEDIFF,如果值为非NULL

时间:2016-01-08 09:00:47

标签: mysql datediff

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

我使用以下语法

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

我现在想要的是仅在SUM

时计算DATEDIFF的{​​{1}}

我尝试了以下查询。

e.time_period_from is NOT NULL

这给了我SQL语法错误。

如何去做?

更新:

这是我的完整MySQL查询

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)

如你所见,这是一个子选择我不能把where条件放在它之外。

这是我得到的错误。

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

感谢。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

我检查你的查询 这一行的错误

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

使用此代替上面的行代码

 SUM(IF(e.time_period_from IS NOT NULL, DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from), 0));