【问题标题】:Mysql count for every month每个月的Mysql计数
【发布时间】:2014-08-21 03:45:53
【问题描述】:

我有一个如下所示的 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

【问题讨论】:

    标签: php mysql date count


    【解决方案1】:
    select sum(level = 1) as level1count, 
           year(`time`) as year, 
           month(`time`) as month
    from your_table
    group by year(`time`), month(`time`)
    

    【讨论】:

    • 每个月的计数未到来。几个月不见了。
    • @mirzavu 有缺失月份的数据吗?
    【解决方案2】:

    您正在寻找的是所有月份的结果它们存在或不存在于数据库中,对于结果集,您需要在查询中包含所有月份,如联合,然后使用基于年份和月份的条件与您的表保持连接

    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

    比联合更好的方法是创建一个包含所有月份和年份行的表,然后将它与你的表连接

    【讨论】:

      猜你喜欢
      • 2017-12-19
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多