I have this table:
Month Type
JAN A
JAN A
FEB B
FEB B
FEB A
FEB A
I want to run a query that groups by month and counts the occurrences of a type for that month.
So for the table above, the output should be:
A B
JAN 2 0
FEB 2 2
It’s probably not possible, but thought I’d give it a shot.
Thank you.
Unfortunately MySQL does not have a
PIVOTfunction which is basically what you are trying to do. So you will need to use an aggregate function with aCASEstatement:See SQL Fiddle with Demo
Now if you want to perform this dynamically, meaning you do not know ahead of time the columns to transpose, then you should review the following article:
Dynamic pivot tables (transform rows to columns)
Your code would look like this:
See SQL Fiddle with Demo