--USE [tempdb]
--GO
-- Create test tablescreate table table1
(number int, [desc] varchar(20),location int, numberatlocation --GO
-- Create test tablescreate table table1
int)create table table2 (code int, name varchar(20))-- Insert test datainsert into table1 values (12345,'test',1000,5)insert into table1 values (12345,'test',1001,2)insert into table1 values (12345,'test',1002,4)insert into table1 values (12345,'test',1003,9)insert into table1 values (12345,'test',1004,7)insert into table2 values (1000,'loc1')insert into table2 values (1001,'loc2')insert into table2 values (1002,'loc3')insert into table2 values (1003,'loc4')insert into table2 values (1004,'loc5')-- Static PIVOTselect number, [desc], [loc1], [loc2], [loc3], [loc4], [loc5]from (select number, [desc], numberatlocation, namefrom table1 join table2 on table1.location=table2.code)pPIVOT(MAX (numberatlocation) FOR Name IN ( [loc1], [loc2], [loc3], [loc4], [loc5] ))
AS pvtORDER BY number
http://sqlwithmanoj.wordpress.com/2011/01/25/dynamic-pivot/
My previous PIVOT UNPIVOT post describes to organize data in a cross tab fashion or to transpose columns into rows and vice-versa.
This is fine only when you know how many columns you need. But when columns vary according to the query then how could you apply them on your scripts. The only way is to store them in a string variable at runtime and apply them in a dynamic SQL query, shown below.
This problem was also discussed on MSDN’s following link: http://social.msdn.microsoft.com/Forums/en/transactsql/thread/26f86fd6-6d06-4cc5-9723-9ee4685bd48a where I proposed an answer also described below:
1 | -- Final Cleanup |
2 | drop table table1 |
3 | drop table table2 |
Comments
Post a Comment