I would suggest you look at the [PIVOT][1] statement, as this sort of thing is what it's there for,
Here's an example of how it might look for you:
First off, we set up a temporary table variable to hold your intermediate values - your source data
declare @t table (account_id varchar(10), TransactionType char(2), Amount money, Account_Balance money)
and now we populate that table (in this case with a couple of SELECT statements)
insert into @t
select '1017', 'CR', 4000, 721999 union all select '1017', 'DR', 2000, 721999
And now here's the good stuff:
select Account_ID, [CR], [DR], Account_Balance
FROM
(SELECT Account_ID, TransactionType, Amount, Account_Balance FROM @t) AS Src
PIVOT ( SUM(Amount) FOR TransactionType IN ([CR], [DR])) AS pvt
edit
-
the bit you want to change to match your query is the Src table definition - so you need to substitute the parenthesised `SELECT Account_ID...FROM @t` statement, leaving the parentheses and the `AS Src` bits in place.
[1]: http://msdn.microsoft.com/en-us/library/ms177410.aspx
↧