Mysql
 sql >> Database >  >> RDS >> Mysql

MySql traspone riga in colonna e colonna in riga

Puoi farlo in questo modo

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')

Uscita:

| 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 |

Ecco SQLFiddle demo