mysql - SQL - Create pivot table -


i'm trying create pivot table data in number of tables, can't work. database structure:

enter image description here

so tables like:

enter image description here

what create pivot table combining sales data customers per product this:

enter image description here

(this data fed different system requires input, can't change format)

however, have no idea how accomplish this. tried this:

select distinct c.name,         p.name,        sum(p.price)         customer c   left join sale s on c.customerid = s.customerid   left outer join product p on s.productid = p.productid group s.productid, s.customerid 

i know it's not much, i'm having hard time wrapping head around it. can me on track?

cheers, cj

its easy, can pivot custom case when statements:

select c.name,  sum(case when p.name = 'product x' p.price else 0 end) "product x", sum(case when p.name = 'product y' p.price else 0 end) "product y", sum(case when p.name = 'product z' p.price else 0 end) "product z"     customer c       left join sale s on c.customerid = s.customerid       left outer join product p on s.productid = p.productid     group c.customerid, c.name 

Comments