I’ve just started to get into SQL Server deeper and I have a problem. I have to transform a row into a column, but I can’t figure it out.
The row looks like this:
Columns: T1 T2 T3 .........T20
Values: 1 0 9 ......... 15
I want to receive something like this:
Col Val
________
T1 1
T2 0
T3 9
........
T20 15
I know i have to use a pivot, i have read about this, but can’t figure it out
You have to use
UNPIVOTtable operator for this, like this:SQL Fiddle Demo.
Update 1
If you want to do this dynamically for any number of columns, without the need to write them manually, the only way I can think of is by reading these columns from the table
information_schema.columnsto get the list of columns’ names of the table. Then use dynamic SQL to compose the statementFOR col IN ...dynamically like this:Updated SQL Fiddle Demo
This will give you: