table
id | name | year
Data:
1 | ham | 2006
2 | ham | 2007
3 | ham | 2008
4 | amm | 2007
5 | amm | 2008
6 | inn | 2009
Now i’m trying to construct a sql that gives me the following output (or similar)
name | y1 | y2 | y3 | y4
ham | 2006 | 2007 | 2008 | null
amm | null | 2007 | 2008 | null
inn | null | null | null | 2009
When doing multiple (self) left joins I kind of gets this, but only if 2006 is set for that name. Is there a way to achieve this?
You want what is called a “pivot”, and call you need is a conditional
sum:No joins, no muss, no fuss. And it will perform really well.
This works because in mysql,
trueis1andfalseis0, so summing a condition counts how many times it was true!Note that this will give you zeroes instead of
nulls for “no data” years, which is probably better. If you really want nulls, useif(sum(year = 2006) = 0, null, sum(year = 2006)) as y1etc, but hopefully you don’t need it.