Jeg testede følgende på MySQL 8.0.1:
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';
Brug af QUOTE()-funktionen gør det enklere, fordi det eliminerer behovet for at finde ud af de tredobbelte vs. quad-anførselstegn.
Output:
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
Så kopierede og indsatte jeg for at køre den forespørgsel og fik dette output:
+--------------+------------+---------+
| 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 |
+--------------+------------+---------+
Jeg har lige indlæst mine testdata med dine første tre datoers data.