如何在mysql中按组累计求和

时间:2016-02-29 19:50:21

标签: mysql sql select group-by

我想知道有多少活跃学生按月出席统计工作。

目前的数据就像这个虚拟表:

start_date  quit_date   dummyName
-----------------------------------------
2015-09-12  2015-12-12  foo
2015-10-12  2015-12-12  bar
2015-10-13  2015-12-12  bob
2015-10-13  2015-12-12  rich
2015-12-13  2015-12-31  eve

结果将按月分组。 GROUP BY和SUM不起作用,它必须像这样累积:

month       count
-----------------
2015-08     0    # no student added
2015-09     1    # just one student was added in this month
2015-10     4    # three more students added in october
2015-11     4    # no student added
2015-12     5    # one more student added
2016-01     0    # all students quits in december, so january there is no students

我该如何进行这样的查询?

1 个答案:

答案 0 :(得分:2)

对于像这样的少数行,您可以创建一个包含要报告的日期的表并使用相关的子查询:

select date_format(eom, '%Y-%m') as yyyymm,
       (select count(*) 
        from dummy du
        where du.start_date <= d.eom and
              du.quit_date > d.eom
       ) NumStudents
from (select date('2015-08-31') as eom union all
      select date('2015-09-30') as eom union all
      select date('2015-10-31') as eom union all
      select date('2015-11-30') as eom union all
      select date('2015-12-31') as eom union all
      select date('2016-01-31') as eom
     ) d;