我有下表:-
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
答案 0 :(得分:1)
您正在寻找从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;
答案 1 :(得分:1)
您可以使用此查询来获得所需的结果:
select
PolicyNumber,
TransactionDate,
[Value],
RunningTotal = SUM([Value]) OVER (PARTITION BY PolicyNumber
order by (PolicyNumber)
rows unbounded preceding)
from [dbo].[Q51340534]
这用简单的英语来说是什么意思:通过PolicyNumber创建数据组,并为每个组保留前Value
列的运行总计。组更改后(PolicyNumber更改),然后重新开始总计。