4

我有一个如下的 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

我想我需要某种for(每个日期)......但没有线索。


只是我在 Eric 的回答之后使用的最后一个查询。(谢谢)。

选择 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
4

3 回答 3

6

好吧,我认为这会起作用,但不确定性能如何:

SELECT t1.date, sum(t2.count)
FROM mytable t1 INNER JOIN mytable t2 ON t2.date <= t1.date
GROUP BY t1.date
于 2010-06-22T16:38:09.243 回答
4

无需加入即可解决此问题。

SET @cumulative_sum := 0;
SELECT date, @cumulative_sum := @cumulative_sum + count AS cumulative_sum
FROM table
ORDER BY date ASC
于 2010-06-22T20:06:00.183 回答
-1

使用 <= 进行自连接并对行求和即可完成此操作。

于 2010-06-22T16:38:17.917 回答