2

Given the table:

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

How do I update cumulative_sum of the rows ordered by date, id?

The result should be:

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

Is it also possible to update only those rows that need to be recalculated when I insert or update a row?

4

3 に答える 3

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と日付が常に昇順である場合に機能します。

于 2012-12-25T15:58:35.163 に答える
0

First sort the table in the desired order and then use below query put it into #temp

Declare @count int=0

UPdate #temp Set @count = cumulative_sum =  count + @count
于 2017-01-20T13:29:18.227 に答える
-1

Use ORDER BY function for date column.

SELECT * FROM yourTableName ORDER BY date

于 2012-12-25T15:29:01.047 に答える