0

I have a table with the following (very simplified) data:

ID   Value1   Value2   Value3
-----------------------------
1    5        7        Test
2    4        7        Test2

I want to get each column name and the value in the row for that column; so, my desired output would look like this:

Column        1        2
----------------------------
Value1        5        4
Value2        7        7
Value3        Test     Test2

I've been playing with PIVOT and UNPIVOT but can't quite figure it out. Any help would be appreciated.

SQLFiddle here.

zimdanen
  • 5,508
  • 7
  • 44
  • 89

1 Answers1

2

For me, what comes to mind is a union all with conditional aggregation:

select 'Value1',
       max(case when id = 1 then value1 end) as [1],
       max(case when id = 2 then value1 end) as [2]
from t
union all
select 'Value2',
       max(case when id = 1 then value2 end) as [1],
       max(case when id = 2 then value2 end) as [2]
from t
select 'Value3',
       max(case when id = 1 then value3 end) as [1],
       max(case when id = 2 then value3 end) as [2]
from t;

I think you can do it with pivot/unpivot, but I think this is simpler.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786