0

I need to convert the column into row using SQL query.

I have table with below structure. Table data:

enter image description here

and I need to convert column value into rows like below

Expected data structure:

enter image description here

All help is greatly appreciated

Dale K
  • 21,987
  • 13
  • 41
  • 69

1 Answers1

2

This is an unpivot-repivot problem. Here is a solution:

select v.id,
       max(case when t.id = 1 then v.val end) as val_1,
       max(case when t.id = 2 then v.val end) as val_2,
       max(case when t.id = 3 then v.val end) as val_3,
       max(case when t.id = 4 then v.val end) as val_4,
       max(case when t.id = 5 then v.val end) as val_5
from t cross apply
     (values ('Run', run),
             ('Temp', temp),
             ('RG', RG),
             ('FF', FF)
     ) which (id, val)
group by v.id;
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709