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

How to turn data with pivot?

Data:

CASEID VISITDATE QUESTION ANSWER COMEFROM
1 2021-01-02 Q1 1 H
1 2021-01-02 Q2 2 O
1 2021-01-02 Q3 3 B
1 2021-01-08 Q1 4 H
1 2021-01-08 Q2 5 O
1 2021-01-08 Q3 6 B

Expected result:

CASEID VISITDATE Q1 Q2 Q3
1 2021-01-02 1 2 3
1 2021-01-08 4 5 6

My code:

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 CaseID, Visitdate, [Q1], [Q2], [Q3]

from

(
 select CaseID, Visitdate, Question, ANSWER, COMEFROM

 from DATA
          ) as v

pivot

(
 MAX(ANSWER) 
    
 FOR Question IN ([Q1], [Q2], [Q3])
                                    ) as p

OUTPUT:

CASEID VISITDATE Q1 Q2 Q3
1 2021-01-02 1 null null
1 2021-01-02 null 2 null
1 2021-01-02 null null 3
1 2021-01-08 4 null null
1 2021-01-08 null 5 null
1 2021-01-08 null null 6

>Solution :

You can use below PIVOT code. When you do pivot , the columns not in the pivot are by default applied grouping.

declare @table table(CaseId int,    VisitDate   date, Question char(2), Answer int)

insert into @table values
(1  ,'2021-01-02','Q1',1)
,(1 ,'2021-01-02','Q2',2)
,(1 ,'2021-01-02','Q3',3)
,(1 ,'2021-01-08','Q1',4)
,(1 ,'2021-01-08','Q2',5)
,(1 ,'2021-01-08','Q3',6)

SELECT * FROM @table
PIVOT
(
MAX(Answer) FOR Question in ([Q1],[Q2],[Q3])
) as pvt
CaseId VisitDate Q1 Q2 Q3
1 2021-01-02 1 2 3
1 2021-01-08 4 5 6
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