繁体   English   中英

如何在MySQL中按组累计总和

[英]How to cumulative sum by group in mysql

我想知道每个月有多少在职学生出于统计目的。

当前数据类似于此伪表:

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

我该如何查询?

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM