累积天数

时间:2010-06-22 16:31:18

标签: mysql aggregate-functions

我有一个如下的MySQL表:

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

如何累计每一天的总和到下一个?结果如下:

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

我想我需要一些(每个日期)......但没有任何线索。


我在Eric的回答后使用的最终查询。 (感谢)。

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

3 个答案:

答案 0 :(得分:6)

嗯,我认为这样可行,但不确定性能如何:

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

答案 1 :(得分:4)

没有加入就可以解决这个问题。

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

答案 2 :(得分:-1)

使用&lt; =自联接,并且该行可以实现此目的。