为多列编写SQL Unpivot运算符-数据堆栈

时间:2019-04-28 11:33:22

标签: sql

我正在尝试使用SQL中的UNPIVOT运算符堆叠数据集,但是当有多个列需要取消透视时,我不知道如何执行该运算符。

这是当前的数据结构:

Input

这是我想要的输出:

Output

谁能帮我编写SQL代码,以将数据提取到未透视的结构中?

1 个答案:

答案 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
. . .

某些数据库支持横向联接,这将简化逻辑。但是您尚未指定数据库。