[英]Need help on unpivot in mysql with multiple date columns
Here is my input. 这是我的意见。 I want to see my output like : (I am trying to do unpivot in mysql data transform in Domo) 我想看到我的输出,如:(我正在尝试在Domo的mysql数据转换中进行透视)
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. PS:我尝试使用堆栈溢出时可用的所有帮助。 But non were helpful in my case. 但是在我的情况下,没有帮助。
I tested the following on MySQL 8.0.1: 我在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. 使用QUOTE()函数使其更简单,因为它不需要找出三重引用与四重引用。
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. 我只是用前三个日期的数据加载了测试数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.