我有一个看起来像这样的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
答案 0 :(得分:2)
您正在寻找的是将所有月份的结果存在或不存在于数据库中,对于结果集,您需要在所有月份进行查询,例如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)
比联盟更好的方法是拥有一个包含所有月份年份表的表格,然后将其与表格一起加入
答案 1 :(得分:0)
select sum(level = 1) as level1count,
year(`time`) as year,
month(`time`) as month
from your_table
group by year(`time`), month(`time`)