我正在尝试使用SQL中的UNPIVOT运算符堆叠数据集,但是当有多个列需要取消透视时,我不知道如何执行该运算符。
这是当前的数据结构:
这是我想要的输出:
谁能帮我编写SQL代码,以将数据提取到未透视的结构中?
答案 0 :(得分:0)
您的数据格式非常差。一种方法是将每个组合作为一个单独的查询进行查询,然后将其与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
. . .
某些数据库支持横向联接,这将简化逻辑。但是您尚未指定数据库。