有一张表有这样的数据:
-----------------------
| id | date |
-----------------------
| 1 | 2016-07-11 |
| 2 | 2016-07-11 |
| 3 | 2016-07-15 |
| 4 | 2016-07-15 |
| 5 | 2016-07-15 |
| 6 | 2016-07-16 |
| 7 | 2016-07-19 |
| 8 | 2016-07-20 |
-----------------------
我想得到一个日期范围(所有日期)和每个日期的ID计数,当没有记录时返回0。
如果在2016-07-10至2016-07-20之间运行日期,结果应如下所示:
--------------------------
| date | count(id) |
--------------------------
| 2016-07-10 | 0 |
| 2016-07-11 | 2 |
| 2016-07-12 | 0 |
| 2016-07-13 | 0 |
| 2016-07-14 | 0 |
| 2016-07-15 | 3 |
| 2016-07-16 | 1 |
| 2016-07-17 | 0 |
| 2016-07-18 | 0 |
| 2016-07-19 | 1 |
| 2016-07-20 | 1 |
--------------------------
我找到了getting a date range的解决方案,但无法弄清楚如何计算表中这些日期的ID。
谢谢!
答案 0 :(得分:5)
我通过修改解决方案中给出的获取所有日期的查询来解决这个问题。
以下查询返回所有日期,如果存在任何记录,则返回ID计数:
select d.date, count(v.id) 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) d
left join visitors v on d.date = v.date
where d.date between '2016-06-01' and '2016-06-30'
group by d.date
order by d.date
感谢获取日期范围到@mark-bannister以及查询匹配结果的简单连接,并且排序可以获得解决方案。
答案 1 :(得分:0)
请尝试以下操作,基本上需要一个可以帮助您获得所需结果的分组。也可以根据需要使用范围的where条件
SELECT date ,count(date) from datetable group by date;
答案 2 :(得分:-2)
简单地说,
WHERE `date` BETWEEN '2016-07-10' AND '2016-07-20'