0
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
预期结果
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
预期结果
你可以创建日期的列表,你可以用来列出并加入你的桌子。以下查询中的表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 BETWEEN '2017年8月30日' 和 '2017年9月6日',可以使用所产生的MIN
( )和MAX()在你的表中创建一个子查询列
酷的数据显示的问题,所以只需使用这一个,并添加左连接到我们的表,修理我的麻烦,谢谢。 –
你需要创建一个临时表[WITH],它产生你感兴趣的所有日期和LEFT JOIN与你的查询。我认为这是一个公开的问题,我已经看过很多次了! –
一些想法在https://stackoverflow.com/questions/1046865/mysql-select-all-dates-in-a-range-even-if-no-records-present – EdmCoff
请帮助我,我试图解决从现有问题,但徒劳 –