在 Oracle 中使用标志逆透视
unpivot with a flag in Oracle
我有这个table结构
ID,SUPPLIER_GROUP1,SUPPLIER1,SUPPLIER_GROUP2,SUPPLIER2.
我想反轴并得到
ID,SUPPLIER_GROUP,供应商,类型
所以每个 supplier_group 和供应商的值都会出现在适当的列中,并且在 TYPE 列中将是 1 或 2 以查看 SUPPLIER_GROUP 和 SUPPLIER 值是 supplier1 还是 supplier2 。
对多个列组使用 UNPIVOT
:
SELECT *
FROM table_name
UNPIVOT (
(supplier_group, supplier) FOR type IN (
(supplier_group1, supplier1) AS 1,
(supplier_group2, supplier2) AS 2
)
);
其中,对于示例数据:
CREATE TABLE table_name (ID,SUPPLIER_GROUP1,SUPPLIER1,SUPPLIER_GROUP2,SUPPLIER2) AS
SELECT 1, 'sg1.1', 's1.1', 'sg2.1', 's2.1' FROM DUAL UNION ALL
SELECT 2, 'sg1.2', 's1.2', 'sg2.2', 's2.2' FROM DUAL UNION ALL
SELECT 3, 'sg1.3', 's1.3', 'sg2.3', 's2.3' FROM DUAL
输出:
ID
TYPE
SUPPLIER_GROUP
SUPPLIER
1
1
sg1.1
s1.1
1
2
sg2.1
s2.1
2
1
sg1.2
s1.2
2
2
sg2.2
s2.2
3
1
sg1.3
s1.3
3
2
sg2.3
s2.3
db<>fiddle here
我有这个table结构
ID,SUPPLIER_GROUP1,SUPPLIER1,SUPPLIER_GROUP2,SUPPLIER2.
我想反轴并得到
ID,SUPPLIER_GROUP,供应商,类型
所以每个 supplier_group 和供应商的值都会出现在适当的列中,并且在 TYPE 列中将是 1 或 2 以查看 SUPPLIER_GROUP 和 SUPPLIER 值是 supplier1 还是 supplier2 。
对多个列组使用 UNPIVOT
:
SELECT *
FROM table_name
UNPIVOT (
(supplier_group, supplier) FOR type IN (
(supplier_group1, supplier1) AS 1,
(supplier_group2, supplier2) AS 2
)
);
其中,对于示例数据:
CREATE TABLE table_name (ID,SUPPLIER_GROUP1,SUPPLIER1,SUPPLIER_GROUP2,SUPPLIER2) AS
SELECT 1, 'sg1.1', 's1.1', 'sg2.1', 's2.1' FROM DUAL UNION ALL
SELECT 2, 'sg1.2', 's1.2', 'sg2.2', 's2.2' FROM DUAL UNION ALL
SELECT 3, 'sg1.3', 's1.3', 'sg2.3', 's2.3' FROM DUAL
输出:
ID TYPE SUPPLIER_GROUP SUPPLIER 1 1 sg1.1 s1.1 1 2 sg2.1 s2.1 2 1 sg1.2 s1.2 2 2 sg2.2 s2.2 3 1 sg1.3 s1.3 3 2 sg2.3 s2.3
db<>fiddle here