php – 每个月的Mysql数

我有一个
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更好的方法是创建一个包含所有月份和年份行的表格,然后将其与您的表格一起加入

点赞