Was Sie tun müssen, ist zuerst, deaktivieren Sie die Daten und dann schwenken Sie sie. Aber leider hat MySQL diese Funktionen nicht, deshalb müssen Sie sie replizieren, indem Sie eine UNION ALL
Abfrage für das Unpivot und eine Aggregatfunktion mit einem CASE
für den Pivot verwenden.
Die Entpivotisierung oder UNION ALL
Stück nimmt die Daten von Ihrem col1, col2, etc und verwandelt es in mehrere Zeilen:
select id, month, col1 value, 'col1' descrip
from yourtable
union all
select id, month, col2 value, 'col2' descrip
from yourtable
union all
select id, month, col3 value, 'col3' descrip
from yourtable
union all
select id, month, col4 value, 'col4' descrip
from yourtable
SQL Fiddle with Demo See.
Ergebnis:
| ID | MONTH | VALUE | DESCRIP |
----------------------------------
| 101 | Jan | A | col1 |
| 102 | feb | C | col1 |
| 101 | Jan | B | col2 |
| 102 | feb | A | col2 |
| 101 | Jan | (null) | col3 |
| 102 | feb | G | col3 |
| 101 | Jan | B | col4 |
| 102 | feb | E | col4 |
Sie dann diese wickeln in einer Unterabfrage das Aggregat zu übernehmen und das CASE
diese in das Format konvertieren Sie wollen:
select descrip,
max(case when month = 'jan' then value else 0 end) jan,
max(case when month = 'feb' then value else 0 end) feb
from
(
select id, month, col1 value, 'col1' descrip
from yourtable
union all
select id, month, col2 value, 'col2' descrip
from yourtable
union all
select id, month, col3 value, 'col3' descrip
from yourtable
union all
select id, month, col4 value, 'col4' descrip
from yourtable
) src
group by descrip
Siehe SQL Fiddle with demo
Die Ergebnis ist:
| DESCRIP | JAN | FEB |
-----------------------
| col1 | A | C |
| col2 | B | A |
| col3 | 0 | G |
| col4 | B | E |
Willkommen bei stackoverflow. [Dies ist eine sehr häufige Frage] (http://stackoverflow.com/search?q= [mysql] + pivot). Bitte nehmen Sie sich ein paar Minuten Zeit, um die Archive zu durchsuchen. Versuchen Sie zuerst, eine der vorherigen Antworten anzupassen. Dann, wenn Sie auf Probleme stoßen, posten Sie Ihre Anfrage und eventuelle Fehler hier. – Leigh
möglich Duplikat von [MySQL Pivot-Zeile in dynamische Anzahl von Spalten] (http://stackoverflow.com/questions/12004603/mysql-pivot-row-into-dynamic-number-of-columns) – RichardTheKiwi