How to convert Columns to row in TSQL

pizaro 101 Reputation points
2022-09-15T18:32:45.06+00:00

Pls i need help with how to come up with a script to convert columns to rows like this.

this is how my table looks like:

241559-image.png

And this is how i want my Final results or new table to look like to be:

241603-image.png

Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-09-15T18:53:34.777+00:00

    Try:

    select row_id, payor, type, flag  
    from MyTable  
    unpivot ( flag for type in (pvd, chf2, depression) ) u  
    

    To create a new table:

    select row_id, payor, type, flag  
    into MyNewTable  
    from MyTable   
    unpivot ( flag for type in (pvd, chf2, depression) ) u  
    
    2 people found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-09-15T19:58:24.65+00:00
    create table test1 (row_id int,payor varchar(20),pvd int,   chf2 int, depression int)  
      
    insert into test1 values (33,'kcc',1,0,0 )  
      
      
    select  row_id,payor, type,flag  
    from   test1   
    cross apply (values('pvd',pvd),('chf2',chf2),('depression',depression)) d (type,flag)  
      
    drop table test1   
    
    3 people found this answer helpful.

  2. Wilko van de Velde 2,236 Reputation points
    2022-09-16T07:21:02.817+00:00
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.