Skip to content
Advertisement

Transpose row to column in SQL Server

I have a table like below:

The first row is the header. Now, I would like to transpose table into this

I have tried unpivot but the result is not desired table.

Thanks in advance,

Advertisement

Answer

I recommend using cross apply to unpivot and then aggregation:

I much, much prefer this over pivot/unpivot. Why? APPLY implements a lateral join, which is a powerful construct in SQL (and part of the SQL standard albeit with slightly different syntax). Unpivoting is a nice introduction to this feature.

The pivoting functions are bespoke functions and not part of the standard. They also do not generalize in any way, being designed for a single purpose.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement