Cumulative sum over days

↘锁芯ラ 提交于 2019-12-10 09:05:32

问题


I have a MySQL table like the following:

date         count
2010-01-01   5
2010-01-02   6
2010-01-03   7

How can I accumulate the sum of each day to the next one? So the result is like:

date         acum per day
2010-01-01   5
2010-01-02   11
2010-01-03   18

I think i need some kind of for(each date)... but no clue.


Just the final query i used following answer from Eric. (thanks).

SELECT t1.dia, sum(t2.operacions), sum(t2.amount) FROM

(SELECT count(*) operations, sum(amount), date(b.timestamp) dia
    FROM transactions b group by date(b.timestamp)) t1 

INNER JOIN 

(SELECT count(*) operations, sum(amount), date(b.timestamp) dia
    FROM transactions b group by date(b.timestamp)) t2 

ON t2.dia <= t1.dia GROUP BY t1.dia

回答1:


Well, I think this would work, not sure how the performance would be though:

SELECT t1.date, sum(t2.count)
FROM mytable t1 INNER JOIN mytable t2 ON t2.date <= t1.date
GROUP BY t1.date



回答2:


It's possible to solve this problem without join.

SET @cumulative_sum := 0;
SELECT date, @cumulative_sum := @cumulative_sum + count AS cumulative_sum
FROM table
ORDER BY date ASC



回答3:


Self join with a <= and sum the row would accomplish this.



来源:https://stackoverflow.com/questions/3095135/cumulative-sum-over-days

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!