MySql : fill a column thanks to a IF condition ? (see example inside ;) )

Issue

I have a database table that looks like this:

Name Town Type Brand Ref
Smith London Big Sony 1020
Carlos Rio Big Nokia 050
Francois Paris Little Sony 250

I need to get:

Name Town Big_Sony Big_Nokia Little_Sony Little_Nokia
Smith London 1020
Carlos Rio 050
Francois Paris 250

Is there any possibility, with IF condition, to fill the right column?

I don’t really know if I’d be possible to do it…

Thanks you for your precious help 🙂

edit : I tried the Forpas suggestion, but I just add

Name Town Type Brand Ref
Roberto Roma Little Sony 100

but I have not more result 🙁 see here

Solution

You need conditional aggregation:

SELECT Name, Town,
       MAX(CASE WHEN Type = 'Big' AND Brand = 'Sony' THEN Ref END) Big_Sony,
       MAX(CASE WHEN Type = 'Big' AND Brand = 'Nokia' THEN Ref END) Big_Nokia,
       MAX(CASE WHEN Type = 'Little' AND Brand = 'Sony' THEN Ref END) Little_Sony,
       MAX(CASE WHEN Type = 'Little' AND Brand = 'Nokia' THEN Ref END) Little_Nokia
FROM tablename
GROUP BY Name, Town 

See the demo.
Results:

Name Town Big_Sony Big_Nokia Little_Sony Little_Nokia
Carlos Rio null 50 null null
Francois Paris null null 250 null
Smith London 1020 null null null

Answered By – forpas

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published