2016-01-08 57 views
0

这是我之前发布的question的后续行为。DATEDIFF如果值不为NULL

我使用的语法如下计算DATEDIFF的SUM

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

我现在要的是计算DATEDIFFSUM只有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" 

谢谢。

+0

什么是错误 –

+1

我想你刚刚得到括号ng,IF有3个参数,第一个是条件,第二个是条件为真的值,第三个是假的值。但条件后您的括号关闭 –

+0

@VipinJain让我更新。 –

回答

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) 
+0

谢谢凯指出,它工作:) –

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));