兩列

2012-12-25 26 views
2

下令更新累計總和鑑於表:兩列

id date count cumulative_sum 
1 2 100     
2 1 50 
3 1 10 
4 2 5 

如何更新行cumulative_sum通過dateid有序?

結果應該是:

id date count cumulative_sum 
2 1 50 50 
3 1 10 60 
1 2 100 160 
4 2 5  165 

是否也可以只更新那些需要重新計算,當我插入或更新行的行?

回答

1

您可以使用此:

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和日期總是按升序排列,這將起作用。

-1

使用ORDER BY功能爲date列。

SELECT * FROM yourTableName ORDER BY date

0

首先排序所需順序表,然後使用下面的查詢放入#temp

Declare @count int=0 

UPdate #temp Set @count = cumulative_sum = count + @count