SQL Server T-SQL - Update column with calculated values from previous rows [duplicate]

hjzp0vay  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(125)

This question already has answers here:

Is there a way to access the "previous row" value in a SELECT statement? (9 answers)
Closed 5 days ago.

Here is my sample data

declare @MyTable TABLE(ClientId int, RecNo int, PaidAmt decimal(12, 2), PaidBefore decimal(12,2),
    ReimbToDate decimal(12,2), CanReimb decimal(12,2), BalBeforeReimb decimal(12, 2), 
    ReimbAmt decimal(12, 2), BalAfterReimb decimal(12, 2) )

insert into @MyTable (ClientId, RecNo, PaidAmt, PaidBefore, ReimbToDate, CanReimb, BalBeforeReimb ) select 1, 1, 100, 0, 0, 0 ,250
insert into @MyTable (ClientId, RecNo, PaidAmt, PaidBefore, ReimbToDate) select 1, 2, 400, 0, 0
insert into @MyTable (ClientId, RecNo, PaidAmt, PaidBefore, ReimbToDate) select 1, 3,-200 ,0 ,0

insert into @MyTable (ClientId ,RecNo ,PaidAmt ,PaidBefore ,ReimbToDate ,CanReimb,BalBeforeReimb) select 2 ,1 ,900 ,0 ,0 ,0 ,3000
insert into @MyTable (ClientId ,RecNo ,PaidAmt ,PaidBefore ,ReimbToDate) select 2 ,2 ,300 ,0 ,0
insert into @MyTable (ClientId ,RecNo ,PaidAmt ,PaidBefore ,ReimbToDate) select 2 ,3 ,1600 ,0 ,0
insert into @MyTable (ClientId ,RecNo ,PaidAmt ,PaidBefore ,ReimbToDate) select 2 ,4 ,-900 ,900 ,900
insert into @MyTable (ClientId ,RecNo ,PaidAmt ,PaidBefore ,ReimbToDate) select 2 ,5 ,-300 ,300 ,300
insert into @MyTable (ClientId ,RecNo,PaidAmt,PaidBefore,ReimbToDate) select 2,6,750,0,0
insert into @MyTable (ClientId ,RecNo,PaidAmt,PaidBefore,ReimbToDate) select 2,7,625,0,0
insert into @MyTable (ClientId ,RecNo,PaidAmt,PaidBefore,ReimbToDate) select 2,8,125,625,625

Other Columns are calculated as follow:

CanReimb = PaidAmt + PaidBefore - ReimbToDate

BalBeforeReimb is BalAfterReimb of previous row of same client when RecNo is not 1

ReimbAmt is minimum of CanReimb and BalBeforeReimb

BalAfterReimb = BalBeforeReimb - ReimbAmt

I need output as follow:

Can anyone please help?

bfrts1fy

bfrts1fy1#

I wrote the code based on your request, because I don't know the data, I didn't test the data

select 
ClientId
,RecNo
,PaidAmt
,PaidBefore
,CanReimb
,BalBeforeReimb
,ReimbAmt=case when CanReimb<BalBeforeReimb then CanReimb else BalBeforeReimb end,
BalAfterReimb=BalBeforeReimb-ReimbAmt

from (
        select ClientId,RecNo,PaidAmt,PaidBefore,CanReimb,ReimbAmt,case when  RecNo<>1 then 
        LAG (BalBeforeReimb) over (partition by ClientId order by ClientId) else 0 end as BalBeforeReimb

        from @MyTable
)a

dbfiddle

相关问题