[英]How to cumulative sum by group in mysql
I want to know how many active students are present by month for statistics purposes. 我想知道每个月有多少在职学生出于统计目的。
The present data is like this dummy table: 当前数据类似于此伪表:
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
the result would be grouped by month. 结果将按月分组。 GROUP BY and SUM does not works, it must be cumulative like this:
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
How can I do a query like this? 我该如何查询?
For a handful of rows like this, you can create a table with the dates you want to report on and use correlated subqueries: 对于像这样的少数几行,您可以创建一个表,其中包含要报告的日期,并使用相关的子查询:
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.