I am using SQL Server 2005 for my application. I have a table in my stored procedure which has two columns, C1 and C2. I want to transpose this table such that the values of column C1 becomes the columns. Before transpose (Table 1):
C1 C2
M1 U1
M1 U2
M1 U3
M2 U4
M2 U5
After Transpose (Table 2):
M1 M2
U1 U4
U2 U5
U3 NULL
In Table1, the number of distinct values (M1, M2) may vary. So, the columns in Table2 are not fix.
Please provide a solution to achieve the same.
This isnt exact result that you want but you can try this
For this type of data transformation you will want to use the
PIVOT
function that is available in SQL Server 2005+. There are two ways to apply the pivot function.If you know the values ahead of time, then you can hard-code the values in the query. Similar to this:
See SQL Fiddle with Demo.
But if you have an unknown number of values that you want to transpose into columns, then you can use dynamic SQL to create the query at run-time.
See SQL Fiddle with Demo.
Both will give the same result, the difference is the dynamic version is flexible if the values will change:
This is probably a case where dynamic sql is your friend. Assuming your base table's name is "Transpose":
This won't achieve the exact layout your question described because their isn't a key field to group the results by. Instead, the output will look like the following:
If your base table has a key field the query can be modified slightly to group the results by the key field and probably come a bit closer to your stated goal for the resulting data.