显示所有日期之间,即使没有结果在分组中

时间:2017-09-19 21:36:57

标签: mysql sql

SELECT Count(Phq_2) as Phq_2, Date(created) as created
FROM `survey` 
WHERE Phq_2 != '' 
GROUP BY Date(created) 
ORDER BY Date(created) ASC

显示此

This result which is query giving

预期结果

I want this result

1 个答案:

答案 0 :(得分:2)

您可以创建一个日期列表,您可以使用这些日期列出并加入您的表格。下面的查询中的表c是日期表。

SELECT c.date, 
       COUNT(s.phq_2) 
  FROM (select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) date from
        (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
        (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
        (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
        (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
        (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4
       ) c
  LEFT JOIN `survey` s 
    ON c.date = s.created
 WHERE s.phq_2 != '' 
   AND c.date BETWEEN '2017-08-30' AND '2017-09-06'
 GROUP BY c.date
 ORDER BY c.date

结果

date        COUNT(s.phq_2)
2017-08-30  1
2017-08-31  1
2017-09-01  0
2017-09-02  0
2017-09-03  0
2017-09-04  0
2017-09-05  1
2017-09-06  6

如果你想为WHERE c.date确定日期,请在2017-08-30' AND' 2017-09-06',您可以在子查询中使用从表中创建的列的MIN()和MAX()结果