这是我之前发布的question的后续行为。DATEDIFF如果值不为NULL
我使用的语法如下计算DATEDIFF的SUM
SUM(DATEDIFF(COALESCE(e.time_period_to, NOW()), e.time_period_from))/COUNT(DISTINCT e.company_id)
我现在要的是计算DATEDIFF
SUM
只有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语法错误。
如何去呢?
UPDATE:
这里是我的全部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"
谢谢。
什么是错误 –
我想你刚刚得到括号ng,IF有3个参数,第一个是条件,第二个是条件为真的值,第三个是假的值。但条件后您的括号关闭 –
@VipinJain让我更新。 –