我有一个 mysql 表,如下所示:
id level time
1 1 2014-02-19 04:33:04
2 1 2014-03-19 04:33:04
3 1 2014-03-20 04:33:04
4 2 2014-03-21 04:53:04
5 1 2014-07-19 04:33:04
6 2 2014-07-19 04:33:04
7 1 2014-07-19 04:33:04
8 1 2014-08-19 04:33:04
我想像这样获得第 1 级的结果:
level1count year month
0 2014 1
1 2014 2
2 2014 3
0 2014 4
0 2014 5
0 2014 6
2 2014 7
1 2014 8
0 2014 9
0 2014 10
0 2014 11
0 2014 12
我试过这个查询,但没有给出每个月的结果
SELECT YEAR(time) AS year, MONTH(time) AS month, COUNT(DISTINCT id) AS count FROM users where level = '1' GROUP BY year, month
最佳答案
您正在寻找的是让所有月份的结果在数据库中存在或不存在,对于结果集,您需要像 union 一样在查询中拥有所有月份,然后使用基于年份和月份的条件与您的表联接
select coalesce(sum(`level` = 1),0) level1count
coalesce(sum(`level` = 2),0) level2count ,y,m
from
(select 1 as m,2014 as y
union
.
.
.
union
select 12 as m ,2014 as y
) months
left join t on(months.m = month(t.time) and months.y = year(t.time))
group by months.m, year(t.time)
Demo
比 union 更好的方法是有一个包含所有月份和年份行的表,然后将它与你的表连接
关于php - 每个月的Mysql计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24495754/