下令更新累计总和鉴于表:两列
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
是否也可以只更新那些需要重新计算,当我插入或更新行的行?
下令更新累计总和鉴于表:两列
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和日期总是按升序排列,这将起作用。
使用ORDER BY
功能为date
列。
SELECT * FROM yourTableName ORDER BY date
首先排序所需顺序表,然后使用下面的查询放入#temp
Declare @count int=0
UPdate #temp Set @count = cumulative_sum = count + @count