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?
1条答案
按热度按时间bfrts1fy1#
I wrote the code based on your request, because I don't know the data, I didn't test the data
dbfiddle