Here is my input. I want to see my output like : (I am trying to do unpivot in mysql data transform in Domo)
Product Type, Date, Revenue
A, 12-31-2015, 100
B, 12-31-2015, 0
C, 12-31-2015, 200
D, 12-31-2015, 300
E, 12-31-2015, 400
A, 01-31-2016, 400
B, 01-31-2016, 86.88
C, 01-31-2016, 400
D, 01-31-2016, 55
E, 01-31-2016, 455
so on
I am trying to use stored procedure:
create PROCEDURE unpivot_cols()
BEGIN
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT('select `Product Type`, ' '''', COLUMN_NAME, ''' col, ', column_name, ' as value from testing_unpivot'
) separator ' union all '
) INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
where table_name = 'testing_unpivot'
and column_name <> 'Product Type';
set @sql = CONCAT(@sql);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
When i try to execute above procedure , I see no output. Can anyone help me? PS: I tried using all help available on stack overflow. But non were helpful in my case.
I tested the following on 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';
Using the QUOTE() function makes it simpler, because it eliminates the need to figure out the triple vs. quad quotes.
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
Then I did copy & paste to run that query and got this 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 |
+--------------+------------+---------+
I just loaded my test data with your first three dates worth of data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.