Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Transpose Row into Column and Column into Row [duplicate]

i have problem with transposing row to column and column to row. I can do that if it just transpose row to column or column to row.

This my table with data

UNIT|JAN|FEB|MAR|APR|MEI|JUN
CS-1|100|200|300|400|500|600
CS-2|111|222|333|444|555|666
CS-3|331|123|423|923|918|123

and I would like to get the following output

MONTH|CS-1|CS-2|CS-3
JAN  |100 |111 |331
FEB  |200 |222 |123
MAR  |300 |333 |423

etc..

Anybody know how to do this? Thanks very much!

like image 798
danielelisondaya Avatar asked Sep 26 '13 04:09

danielelisondaya


People also ask

How do I transpose rows to columns in MySQL?

If you want to transpose only select row values as columns, you can add WHERE clause in your 1st select GROUP_CONCAT statement. If you want to filter rows in your final pivot table, you can add the WHERE clause in your SET statement.


1 Answers

You can do it this way

SELECT month,
       MAX(CASE WHEN unit = 'CS-1' THEN value END) `CS-1`,
       MAX(CASE WHEN unit = 'CS-2' THEN value END) `CS-2`,
       MAX(CASE WHEN unit = 'CS-3' THEN value END) `CS-3`
  FROM
(
  SELECT unit, month,
         CASE month 
            WHEN 'JAN' THEN jan
            WHEN 'FEB' THEN feb
            WHEN 'MAR' THEN mar
            WHEN 'APR' THEN apr
            WHEN 'MAY' THEN may
            WHEN 'JUN' THEN jun
         END value
    FROM table1 t CROSS JOIN
  (
    SELECT 'JAN' month UNION ALL
    SELECT 'FEB' UNION ALL
    SELECT 'MAR' UNION ALL
    SELECT 'APR' UNION ALL
    SELECT 'MAY' UNION ALL
    SELECT 'JUN'
  ) c
) q
 GROUP BY month
 ORDER BY FIELD(month, 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN')

Output:

| MONTH | CS-1 | CS-2 | CS-3 |
|-------|------|------|------|
|   JAN |  100 |  111 |  331 |
|   FEB |  200 |  222 |  123 |
|   MAR |  300 |  333 |  423 |
|   APR |  400 |  444 |  923 |
|   MAY |  500 |  555 |  918 |
|   JUN |  600 |  666 |  123 |

Here is SQLFiddle demo

like image 183
peterm Avatar answered Sep 20 '22 14:09

peterm