如何总结每个索偿忽略日期的损失金额

时间:2019-02-15 18:42:04

标签: sql sql-server tsql sql-server-2012

我有一个表格,每个交易日期的金额为Loss

如何创建列ClaimLoss来汇总每项索赔的损失金额?

declare @TempTable1 table (ID int, ClaimNumber varchar(100), date date, Loss money)

insert into @TempTable1 
values (1, 'Claim1','2017-01-01', 100),
       (2, 'Claim1','2017-03-06',150),
       (3, 'Claim1','2017-05-01', 50),
       (4, 'Claim2','2018-01-01', 150),
       (5, 'Claim2','2018-08-15', 250),
       (6, 'Claim2','2018-05-03', 350),
       (7, 'Claim3','2018-09-01', 330),
       (8, 'Claim4','2019-01-01', 140),
       (9, 'Claim4','2019-01-13', 225),
       (10, 'Claim5','2019-02-01', 145)

select  ID, 
        ClaimNumber, 
        Date,   
        Loss
from @TempTable1

enter image description here

我需要这样的东西:

enter image description here

是否可以在同一select语句中进行操作?

2 个答案:

答案 0 :(得分:2)

这似乎是使用row_number()case的地方:

select t.*,
       (case when row_number() over (partition by ClaimNumber order by date) = 1
             then sum(loss) over (partition by ClaimNumber) 
             else 0
        end) as claimloss
from @TempTable1 t;

答案 1 :(得分:1)

您可以使用window函数:

select  ID, ClaimNumber, Date, Loss,
        (case when min(id) over (partition by ClaimNumber) = id 
              then sum(loss) over (partition by ClaimNumber) 
              else 0
         end) as claimloss
from @TempTable1;