Home > Mobile >  Move several columns to become rows
Move several columns to become rows

Time:09-01

I have a table

Name   Cost   Total1    
Joe    5      10        
Bob    7      15        
Tom    20     1         

I want to more column Total1 and Total2 to become row for each record and expect result

Name   Cost   Total1    
Joe    5
Joe           10        
Bob    7 
Bob           15        
Tom    20
Tom           1         

My query

select Name, cost, total1
  indicatorname,
  indicatorvalue
from mytable
unpivot
(
  indicatorvalue
  for indicatorname in (total1)
) unpiv;

I don't think it's working. Not sure how to maker it work. Thank you.

CodePudding user response:

select T.name, v.Cost, v.Total1
from T cross apply (values (1, Cost, null), (2, null, Total1)) v(n, Cost, Total1)
order by T.name, v.n;
  • Related