Skip to content
Advertisement

Pivot/Unpivot SQL Result Set Column Names into Separate Column

I have a result set something like this:

Username Birthday Gender
Tom Jan 23 Male

I would like to convert it to something like this:

Name Value
Username Tom
Birthday Jan 23
Gender Male

I’ve been told Pivot/Unpivot was what I was looking for, but I can’t find any info on pulling the column names.

Is there a way to do this?

Advertisement

Answer

You need to use unpivot clause like below :

select *
from Your_Table t
unpivot (
 value for name in (
  Username as 'Username'
, Birthday as 'Birthday'
, Gender as 'Gender'
 )
)
;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement