khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2014-06-03 : 22:42:16
|
[code]declare @tbl1 table( UniqID int, AcctNum int, TranType char, TranDate date, TranAmt int)insert into @tbl1 select 1, 1001123 , 'A' , '11/1/13' , 100insert into @tbl1 select 2, 1010877 , 'B' , '12/2/13' , 10insert into @tbl1 select 7, 1010877 , 'C' , '12/2/13' , 22insert into @tbl1 select 10, 1001123 , 'A' , '12/2/13' , -100insert into @tbl1 select 11, 1001123 , 'B' , '12/6/13' , 145insert into @tbl1 select 12, 1003699 , 'A' , '12/8/13' , 250insert into @tbl1 select 13, 1001123 , 'B' , '1/2/14' , 145insert into @tbl1 select 14, 1003699 , 'C' , '1/4/14' , 110insert into @tbl1 select 15, 1003699 , 'C' , '1/4/14' , -110insert into @tbl1 select 19, 1003699 , 'B' , '1/8/14' , 25insert into @tbl1 select 21, 1001123 , 'B' , '1/2/14' , 80insert into @tbl1 select 22, 1001123 , 'B' , '1/8/14' , 45insert into @tbl1 select 26, 1001123 , 'A' , '1/21/14' , -145declare @tbl2 table( AcctNum int, TranBal int)insert into @tbl2 select 1001123 , 270insert into @tbl2 select 1003699 , 275insert into @tbl2 select 1010877 , 32-- Query; with cte as( select *, rn = row_number() over (partition by AcctNum order by TranDate desc) from @tbl1),rcte as( select c.UniqID, c.AcctNum, c.TranType, c.TranDate, c.TranAmt, b.TranBal, CummAmt = c.TranAmt, c.rn from cte c inner join @tbl2 b on c.AcctNum = b.AcctNum where rn = 1 union all select c.UniqID, c.AcctNum, c.TranType, c.TranDate, c.TranAmt, r.TranBal, CummAmt = r.CummAmt + c.TranAmt, c.rn from cte c inner join rcte r on c.AcctNum = r.AcctNum and c.rn = r.rn + 1 where r.CummAmt <> r.TranBal)select *from rcte where AcctNum = 1001123[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|