Transposing Dynamic Columns to Rows(将动态列转置为行)
问题描述
我想知道如何将 Table_1 反透视为 Expected_Result_Table:
I'd like to know how to unpivot Table_1 into Expected_Result_Table:
Table1
-----------------------------------------
Id abc brt ccc ddq eee fff gga hxx
-----------------------------------------
12345 0 1 0 5 0 2 0 0
21321 0 0 0 0 0 0 0 0
33333 2 0 0 0 0 0 0 0
41414 0 0 0 0 5 0 0 1
55001 0 0 0 0 0 0 0 2
60000 0 0 0 0 0 0 0 0
77777 9 0 3 0 0 0 0 0
Expected_Result_Table
---------------------
Id Word Qty>0
---------------------
12345 brt 1
12345 ddq 5
12345 fff 2
33333 abc 2
41414 eee 5
41414 hxx 1
55001 hxx 2
77777 abc 9
77777 ccc 3
那么,如何转置 Table_1 中的列,从而得到 Expected_Result_Table,只考虑 > 0 的值?
So, How to transpose columns in Table_1 resulting in Expected_Result_Table, considering only values > 0?
推荐答案
MySQL 没有 UNPIVOT 功能,但您可以使用 UNION ALL 将列转换为行.
MySQL does not have an UNPIVOT function, but you can convert your columns into rows using a UNION ALL.
基本语法是:
select id, word, qty
from
(
select id, 'abc' word, abc qty
from yt
where abc > 0
union all
select id, 'brt', brt
from yt
where brt > 0
) d
order by id;
在您的情况下,您声明您需要动态列的解决方案.如果是这种情况,那么您将需要使用准备好的语句来生成动态 SQL:
In your case, you state that you need a solution for dynamic columns. If that is the case, then you will need to use a prepared statement to generate dynamic SQL:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'select id, ''',
c.column_name,
''' as word, ',
c.column_name,
' as qty
from yt
where ',
c.column_name,
' > 0'
) SEPARATOR ' UNION ALL '
) INTO @sql
FROM information_schema.columns c
where c.table_name = 'yt'
and c.column_name not in ('id')
order by c.ordinal_position;
SET @sql
= CONCAT('select id, word, qty
from
(', @sql, ') x order by id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
参见SQL Fiddle with Demo
这篇关于将动态列转置为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将动态列转置为行
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
