You want it to turn out what is called a βrotaryβ one, and you need a conditional sum
:
select name, sum(year = 2006) as y1, sum(year = 2007) as y2, sum(year = 2008) as y3, sum(year = 2009) as y4 from mytable group by name;
No associations, no problems, no problems. And it will work very well.
This works because in mysql true
is 1
and false
is 0
, so summing the condition counts how many times this was true!
Note that this will give you zeros instead of null
for years without data, which is probably better. If you really need zeros, use if(sum(year = 2006) = 0, null, sum(year = 2006)) as y1
etc. But I hope you don't need this.
source share