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.
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 |