给定表:
id date count cumulative_sum
1 2 100
2 1 50
3 1 10
4 2 5
如何更新
cumulative_sum
,date
排序的行中的id
?结果应为:
id date count cumulative_sum
2 1 50 50
3 1 10 60
1 2 100 160
4 2 5 165
当我插入或更新一行时,是否还可以仅更新那些需要重新计算的行?
最佳答案
您可以使用此:
update your_table
set
cumulative_sum = (select sum(c)
from your_table t2
where
t2.date<your_table.date
or (t2.date=your_table.date
and t2.id<=your_table.id));
子查询对计数的累积总和进行计数,该总和是日期小于当前行日期的所有值的总和,或者日期=当前行的日期且id为<的所有值的总和。
您还可以提出以下条件:
where cumulative_sum is null
仅在没有值的情况下才更新行。如果插入表中的所有ID和日期始终按升序排列,则此方法有效。
关于sql - 更新两列排序的累积总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14031864/