MySQL AVG DATEDIFF GROUP BY(如果datetime IS NULL THEN = NOW())

时间:2014-12-02 16:26:13

标签: mysql sql

我试图找出格式化为日期时间的2个字段之间的日期差异。

找到每一行的日期后,从GROUP BY部门计算平均值

这是当前查询,但没有考虑dateClosed IS NULL的位置(请参阅图片)

SELECT ROUND(AVG(DATEDIFF(dateClosed , dateAded) * 1.0), 0) avg
     , department 
  FROM tickets 
 GROUP 
    BY department;

dateAded             dateClosed           dateActivity
2014-07-28 11:43:16  0000-00-00 00:00:00  2014-08-06 10:31:44

因此我需要在查询中包含:

IF dateClosed IS NULL THEN = NOW()

但我不确定如何做到这一点,我尝试了以下但是它不起作用:

SELECT 
round(AVG(DATEDIFF(
CASE WHEN dateClosed IS NULL
THEN SET dateClosed  = NOW()
END
, dateAded) * 1.0), 0) AS avg, department FROM tickets group by department

1 个答案:

答案 0 :(得分:0)

SELECT round(avg(DATEDIFF( IF( dateClosed =  '0000-00-00 00:00:00', NOW(), dateClosed) , dateAded ) * 1.0), 2) AS avg, department
FROM tickets
group by department