Friday, June 14, 2013

SQL Puzzle #7

We have a table variable say MyTable, structure like below.

declare @MyTable Table
(
TrnDate Date, -- Transaction Date
CrDb char(1),  -- Credit/Debit
Amount  money
)

-- Data population
insert into @MyTable values
('01-jul-2012','C',1000),('02-jul-2012','D',200),('03-jul-2012','C',2500),('04-jul-2012','C',800),('05-jul-2012','D',5000)

--select * from @MyTable

we need a single query to get the result as below.

TrnDate    CrDb Amount                Balance
---------- ---- --------------------- ---------------------
2012-07-01 C    1000.00               1000.00
2012-07-02 D    200.00                800.00
2012-07-03 C    2500.00               3300.00
2012-07-04 C    800.00                4100.00
2012-07-05 D    5000.00               -900.00

select TrnDate,CrDb,a.Amount,t.Balance
from @MyTable a
cross apply
(
select sum(case when crdb = 'C' then amount else amount*-1 end) as Balance
from @MyTable b
where  b.TrnDate <= a.TrnDate
) t

No comments:

Post a Comment