PIVOT and UNPIVOT Sample Code


 Create table test  (Name CHAR(1),Forecast INT,Stock INT)    
INSERT into test values ('a',100,300),('b',300,400),( 'a',200,250),('c',200,300)
 

SELECT * FROM (
SELECT * FROM test
UNPIVOT (amt for [grp] IN (Forecast,Stock)) as UnPvt ) t
PIVOT (sum(amt) FOR Name IN (a,b,c)) pvt

 
SELECT grp
,sum(CASE WHEN name = 'a' THEN amt ELSE null END) a
,sum(CASE WHEN name = 'b' THEN amt ELSE null END) b
,sum(CASE WHEN name = 'c' THEN amt ELSE null END) c FROM  test
cross apply (values (Forecast,'Forecast'),(Stock,'Stock')) d(amt,grp) 
Group by grp

drop table test

 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s