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 PIVOT SQL key value pairs

I currently have data and I am looking to pivot the data.

CustomerId BookKey BookValue
John       Title   Goosebumps
John       Count   5
Max        Title   Harry Potter
Max        Count   7
Max        Pages   50

After pivot it should look like

CustomerId Title          Count Pages
John       GooseBumps       5     -
Max        Harry Potter     7     50

I can currently achieve this by repeadedly combining with a left join but there’s a ton of rows. Looking for a way that doesn’t involve so many left joins.

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 cus.*, db2.BookValue as Title, db3.BookValue as Count, db4.BookValue as Pages
from 
(
    select customerid 
    from data_bags db 
    group by customerid 
) cus
left join databags db2 
    on cus.customerid  = db2.customerid  and db2.BookKey  = 'Title'
left join databags db3 
    on cus.customerid  = db3.customerid  and db3.BookKey  = 'Count'
left join databags db4
    on cus.customerid  = db4.customerid  and db4.BookKey  = 'Pages'

....
....

>Solution :

You could use a case expression each wrapped in max().

select 
 customerId, 
 max(case when bookKey = 'Title' then bookValue end) as title, 
 max(case when bookKey = 'Count' then bookValue end) as count, 
 max(case when bookKey = 'Pages' then bookValue end) as pages
from data_bags
group by customerId;
customerid title count pages
Max Harry Potter 7 50
John Goosebumps 5

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