Na MySQL 8.0.1 jsem testoval následující:
SELECT GROUP_CONCAT(
CONCAT(
'SELECT `Product Type`, ',
QUOTE(COLUMN_NAME), ' AS `Date`, ',
'`', COLUMN_NAME, '` AS `Revenue` ',
'FROM testing_unpivot'
) SEPARATOR ' UNION ALL '
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'testing_unpivot'
AND COLUMN_NAME <> 'Product Type';
Pomocí funkce QUOTE() zjednodušuje to, protože eliminuje potřebu zjišťovat uvozovky trojité vs. čtyřnásobné.
Výstup:
SELECT `Product Type`, '01-31-2016' AS `Date`, `01-31-2016` AS `Revenue` FROM testing_unpivot
UNION ALL
SELECT `Product Type`, '02-29-2016' AS `Date`, `02-29-2016` AS `Revenue` FROM testing_unpivot
UNION ALL
SELECT `Product Type`, '12-31-2015' AS `Date`, `12-31-2015` AS `Revenue` FROM testing_unpivot
Pak jsem zkopíroval a vložil, abych spustil tento dotaz, a dostal jsem tento výstup:
+--------------+------------+---------+
| Product Type | Date | Revenue |
+--------------+------------+---------+
| A | 01-31-2016 | 400.00 |
| B | 01-31-2016 | 86.88 |
| C | 01-31-2016 | 400.00 |
| D | 01-31-2016 | 55.00 |
| E | 01-31-2016 | 455.00 |
| A | 02-29-2016 | 55.00 |
| B | 02-29-2016 | 55.00 |
| C | 02-29-2016 | 55.00 |
| D | 02-29-2016 | 11.00 |
| E | 02-29-2016 | 22.00 |
| A | 12-31-2015 | 100.00 |
| B | 12-31-2015 | 0.00 |
| C | 12-31-2015 | 200.00 |
| D | 12-31-2015 | 300.00 |
| E | 12-31-2015 | 400.00 |
+--------------+------------+---------+
Právě jsem načetl svá testovací data s vašimi daty za první tři data.