I have a table as below,
+-----+--------+-----------+----------+
| id | type_id| product_id| date |
+-----+--------+-----------+----------+
| 1 | 1 | 300 |22/01/2013|
| 2 | 1 | 800 |22/01/2013|
| 3 | 1 | 400 |30/01/2013|
| 4 | 1 | 300 |05/02/2013|
| 5 | 5 | 300 |27/02/2013|
| 6 | 1 | 300 |28/02/2013|
| 7 | 3 | 400 |12/03/2013|
| 8 | 5 | 400 |02/03/2013|
| 9 | 1 | 300 |06/03/2013|
| 10 | 1 | 400 |06/03/2013|
| 11 | 5 | 400 |06/03/2013|
| 12 | 1 | 400 |08/03/2013|
Lets say if I want to get count of each type for each product group by month and year, Is this possible? Output that I’m after should be something similar to following..
+-----------+------------+-------------+------------+------+------+
|product_id |count_type_1|count_type_3 |count_tyep_5| month| year |
+-----------+------------+-------------+------------+------+------+
| 300 | 1 | 0 | 0 | 01 | 2013 |
| 800 | 1 | 0 | 0 | 01 | 2013 |
| 400 | 1 | 0 | 0 | 01 | 2013 |
| 300 | 2 | 0 | 1 | 02 | 2013 |
| 300 | 1 | 0 | 0 | 03 | 2013 |
| 400 | 2 | 1 | 2 | 03 | 2013 |
Is this can be achieve using a single SQL?
PS: This is on a MYSQL server
You can use the following to pivot the data which uses an aggregate function and a
CASEexpression to create each column:See SQL Fiddle with Demo
This gives the result: