Thursday, February 17, 2011

Implementation of Pivot & UnPivot

Pivot

[ Just Copy & Paste ]

declare @TBL table(Cust varchar(10),Product varchar(10),QTY int)

insert into @TBL(Cust,Product,QTY) values('C1','P1',5)
insert into @TBL(Cust,Product,QTY) values('C1','P2',2)
insert into @TBL(Cust,Product,QTY) values('C2','P1',1)
insert into @TBL(Cust,Product,QTY) values('C2','P2',10)

select * from @TBL

select Product,C1,C2
from
(
select Cust,Product,QTY from @TBL
) up
pivot (sum(QTY) for Cust in (C1,C2)) as Pvt
order by Product

UnPivot

[ Just Copy & Paste ]

declare @TBL table(Product varchar(10),C1QTY int,C2QTY int)

insert into @TBL(Product,C1QTY,C2QTY) values('P1',5,1)
insert into @TBL(Product,C1QTY,C2QTY) values('P2',2,10)

select * from @TBL

select Cust,Product,QTY
from
(
select Product,C1QTY,C2QTY from @TBL
) up
unpivot (QTY for Cust in (C1QTY,C2QTY)) as UnPvt
order by Cust

No comments:

Post a Comment