Is there a row to column function?
I need to convert some rows into columns in a stored proc.
An y ideas.
Thanks,
Gene
If you're using SQL2005 there is the PIVOT/UNPIVOT functions which are explained nicely in Books Online...|||
if there is multiple columns need to be pivoted, I recommand to use the legacy approach rather new PIVOT operator,
Code Snippet
Create Table #UnPivot
(
Year int,
Product int,
Sales int,
Qty int
)
Insert Into #UnPivot Values(2004,1,28,67);
Insert Into #UnPivot Values(2005,1,15,20);
Insert Into #UnPivot Values(2006,1,50,30);
Insert Into #UnPivot Values(2004,2,5,67);
Insert Into #UnPivot Values(2005,2,6,20);
Insert Into #UnPivot Values(2006,2,10,30);
Select
Product
,Max(Case When Year=2004 then Sales End) [2004-Sales]
,Max(Case When Year=2004 then Qty End) [2004-Qty]
,Max(Case When Year=2005 then Sales End) [2005-Sales]
,Max(Case When Year=2005 then Qty End) [2005-Qty]
,Max(Case When Year=2006 then Sales End) [2006-Sales]
,Max(Case When Year=2006 then Qty End) [2006-Qty]
From
#UnPivot
Group By
product
Drop Table #UnPivot
sql
No comments:
Post a Comment