Friday, April 22, 2011

Pivot to Convert Rows into Columns

 

pivot-sql-server


I need to convert the table as show in the figure above to the one on the right hand side. Using Sql servers Pivot we can easily get this done. Please see the script below:

 

Declare @Table Table(Amount Numeric(18,0), IsCredit Bit)

Insert into @Table(Amount, IsCredit)
Values(1000, 1)
Insert into @Table(Amount, IsCredit)
Values(2000, 1)
Insert into @Table(Amount, IsCredit)
Values(1600, 0)
Insert into @Table(Amount, IsCredit)
Values(2000, 0)

select Amount, IsCredit
from @Table

Select [1] Credit, [0] Debit
From (Select Amount, IsCredit from @Table) As SourceTable
Pivot
(Sum(Amount)
for IsCredit in ([1], [0])
)
As PivotTable;

No comments:

Post a Comment