Skip to content
Advertisement

SQL count when equation of two columns are true

I have a sheet with rows (id and year). See below:

id year
101 2002
101 2006
101 2010
101 2014
101 2018
102 2002
102 2006
102 2010
102 2014
103 2010

I simply want to regroup and reformat my table to look like this:

id 2002 2006 2010 2014 2018
101 1 1 1 1 1
102 1 1 1 1 0
103 0 0 1 0 0

In other words, whenever there is an id with a specific year it will show as a “1” in a field corresponding to that year. Note, that in the sheet there are no other years than the ones above.

I have managed to get the sheet reformatted by

But how to count and fill in the values for each year I don’t find any solution.

Can someone help?

Thanks

Advertisement

Answer

You can use conditional aggregation:

SQL Fiddle

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement