[英]SSMS SQL Need to increment a value for each row for a group
我有下表:-
policy number transaction date value running total
123 26/01/2015 1000.00 0
123 13/02/2017 3000.00 0
234 14/02/2014 500.00 0
234 14/02/2016 4500.00 0
234 23/06/2018 1200.00 0
345 17/07/2017 7000.00 0
我希望它看起來像這樣:-
policy number transaction date value running total
123 26/01/2015 1000.00 1000.00
123 13/02/2017 3000.00 4000.00
234 14/02/2014 500.00 500.00
234 14/02/2016 4500.00 5000.00
234 23/06/2018 1200.00 6200.00
345 17/07/2017 7000.00 7000.00
您正在尋找從SQL Server 2012開始在SQL Server中可用的累積總和窗口函數:
select f.*,
sum(f.value) over (partition by f.policy_number order by f.transaction_date) as running_total
from following f;
您可以使用可更新的CTE將其合並到update
:
with toupdate as (
select f.*,
sum(f.value) over (partition by f.policy_number order by f.transaction_date) as new_running_total
from following f
)
update toupdate
set running_total = new_running_total;
您可以使用此查詢來獲得所需的結果:
select
PolicyNumber,
TransactionDate,
[Value],
RunningTotal = SUM([Value]) OVER (PARTITION BY PolicyNumber
order by (PolicyNumber)
rows unbounded preceding)
from [dbo].[Q51340534]
用簡單的英語來說是什么意思: 通過PolicyNumber創建數據組,並為每個組連續保存前面的Value
列。 組更改后(PolicyNumber更改),然后重新開始總計。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.