Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move several columns to become rows

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading