I have a table like this
+---+-----+----+----+----+----+
|id |month|col1|col2|col3|col4|
+---+-----+----+----+----+----+
|101|Jan |A |B |NULL|B |
+---+-----+----+----+----+----+
|102|feb |C |A |G |E |
+---+-----+----+----+----+----+
And then I want to create report like this
+----+---+---+
|desc|jan|feb|
+----+---+---+
|col1|A |C |
+----+---+---+
|col2|B |A |
+----+---+---+
|col3|0 |G |
+----+---+---+
|Col4|B |E |
+----+---+---+
Can anyone help with this?
What you need to do is first, unpivot the data and then pivot it. But unfortunately MySQL does not have these functions so you will need to replicate them using a
UNION ALL
query for the unpivot and an aggregate function with aCASE
for the pivot.The unpivot or
UNION ALL
piece takes the data from your col1, col2, etc and turns it into multiple rows:See SQL Fiddle with Demo.
Result:
You then wrap this in a subquery to apply the aggregate and the
CASE
to convert this into the format you want:See SQL Fiddle with demo
The result is: