2

I have a table which has data in the below format.

id | col1 | col2 | col3
1  | d11  | d21  | d31
2  | d12  | d22  | d32
3  | d13  | d23  | d33
4  | d14  | d24  | d34
5  | d15  | d25  | d35
6  | d16  | d26  | d36

Is it possible to get the data in the below format.

id    |  1  |  2  |  3  |  4  |  5  |  6
col1  | d11 | d12 | d13 | d14 | d15 | d16
col2  | d21 | d22 | d23 | d24 | d25 | d26
col3  | d31 | d32 | d33 | d34 | d35 | d36

I don't even have a basic idea. Anything is welcome.

Rick James
  • 135,179
  • 13
  • 127
  • 222
Eeshwar Ankathi
  • 260
  • 3
  • 11

2 Answers2

0

You may use this query for your output

with cte as (
select id, 'col1' as col , col1 as val from tab
union all
select id, 'col2' as col , col2 as val from tab
union all
select id, 'col3' as col , col3 as val from tab
)
select id, [1], [2], [3], [4], [5], [6] from (
select id, col, val from cte
) as d
pivot (
max(val) for col in ( [1], [2], [3], [4], [5], [6] )
) as p

Please verify this and see if this works.

DarkRob
  • 3,843
  • 1
  • 10
  • 27
0

You need to unpivot and re-pivot. You can use conditional aggregation:

select col,
       sum(case when id = 1 then val end) as val_1,
       sum(case when id = 2 then val end) as val_2,
       sum(case when id = 3 then val end) as val_3,
       sum(case when id = 4 then val end) as val_4,
       sum(case when id = 5 then val end) as val_5,
       sum(case when id = 6 then val end) as val_6
from ((select id, 'col1' as col, col1 as val from t
      ) union all
      (select id, 'col2' as col, col2 as val from t
      ) union all
      (select id, 'col3' as col, col3 as val from t
      ) 
     ) t
group by col;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786