我有一个表,看起来像这样:
id count
1 100
2 50
3 10
我想添加一个名为cumulative_sum的新列,因此该表将如下所示:
id count cumulative_sum
1 100 100
2 50 150
3 10 160
有没有一条MySQL update语句可以很容易地做到这一点?实现这一目标的最佳方法是什么?
发布于 2010-04-02 06:08:27
如果性能有问题,您可以使用MySQL变量:
set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;
或者,您可以删除cumulative_sum
列并在每个查询上计算它:
set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;
这将以一种运行的方式计算运行和:)
发布于 2010-04-02 05:59:07
UPDATE t
SET cumulative_sum = (
SELECT SUM(x.count)
FROM t x
WHERE x.id <= t.id
)
发布于 2014-07-10 18:06:29
select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;
https://stackoverflow.com/questions/2563918
复制相似问题