sql - 为多列编写 SQL Unpivot 运算符 - 数据堆叠
问题描述
我正在尝试在 SQL 中使用 UNPIVOT 运算符堆叠数据集,但是当有多个列需要取消透视时,我不知道如何执行该运算符。
这是当前的数据结构:
这是我想要的输出:
谁能帮我编写将数据拉入非透视结构的 SQL 代码?
解决方案
您的数据格式很差。一种方法是将每个组合作为单独的查询进行查询,并将它们粘合在一起union all
:
select product, 'Europe' as location, 'Heat Resistant' as properties, 'white' as color
from t
where europe = 'x' and heat_resistant = 'x' and white = 'x'
union all
select product, 'Europe' as location, 'Heat Resistant' as properties, 'blue' as color
from t
where europe = 'x' and heat_resistant = 'x' and blue = 'x'
union all
select product, 'Europe' as location, 'Moisure Resistant' as properties, 'white' as color
from t
where europe = 'x' and moisure_resistant = 'x' and white = 'x'
union all
. . .
一些数据库支持横向连接,这会稍微简化逻辑。但是你还没有指定你的数据库。