Lets say I have this data set:
id city result fruit 1 boston good apple 2 boston bad banana 3 ny good peach 4 ny good banana 5 ny good apple 6 ny bad apple ...
So imagine that this data set goes on and has results for any number of fruit and any number of cities.
The problem is, I don’t know how to perform a query to give me results like this:
city fruit good bad ny bananna 3 2 ny apple 1 3 ny peach 3 2 boston banana 2 5 boston peach 2 1 ...
The idea is that we are grouping by two things, the city and the fruit, but I want to get only the count of fruit within each city. How can I do this?
This technique is generally called a "pivot":
Notice the elegant use of
sum(condition)rather than the mundanesum(case...)Edited
As usual, people can’t help but make critical/irrelevant comments, so for the record…
The
sum(condition)approach works for any database that treatstrueas1andfalseas0. Mysql is one such database, thus this is an appropriate answer for amysqltagged question. Mileage may vary with other databases.