这是我的例子,
WITH TABLE1 (ID,COL1,COL2,SUBCOL1,SUBCOL2)
as (select 1, 'm1',null,'s1',null from dual
union all
select 2, null ,'m2', null,'s2' from dual
)
select * from TABLE1;
从上面的表1中我想创建一个视图,如下所示,
ID | COLTYPE | col | SUBCOLTYPE | subcol
-------------------------------------------------------------
1 COL1 m1 SUBCOL1 s1
2 COL2 m2 SUBCOL2 s2
我所做的是将COL1
,COL2
合并到COL
和SUBCOL1
,SUBCOL2
合并到SUBCOL
。我可以使用UNPIVOT()
函数来实现此目的。
我想象的查询如下,
select * from table1
unpivot(COL for COLTYPE in (COL1,COL2)) --- FIRST MERGE
unpivot(SUBCOL FOR SUBCOLTYPE IN (SUBCOL1,SUBCOL2)) ---SECOND MERGE
;
每个第一和第二合并行在评论其他合并行时单独工作。但他们没有同时工作。如何在同一个select语句中添加多个unpivot()
函数。有可能吗?
答案 0 :(得分:2)
回答原始问题
为什么要使用unpivot?我问,因为你没有将列转换为行。是否保证您要合并的所有列都是NULL,除了其中一列?如果是,您可以使用coalesce功能。
来源数据:
ID COL1 COL2 SUBCOL1 SUBCOL2
---------- -------- -------- -------- --------
1 m1 s1
2 m2 s2
示例:
WITH TABLE1 (ID,COL1,COL2,SUBCOL1,SUBCOL2)
as (select 1, 'm1',null,'s1',null from dual
union all
select 2, null ,'m2', null,'s2' from dual
)
select id,
coalesce(col1,col2) as col,
coalesce(subcol1, subcol2) as subcol
from TABLE1;
结果:
ID COL SUBCOL
---------- -------- --------
1 m1 s1
2 m2 s2
回答更新的问题
编辑完问题后,您可能正在寻找这种语法:
WITH TABLE1 (ID,COL1,COL2,SUBCOL1,SUBCOL2)
as (select 1, 'm1',null,'s1',null from dual
union all
select 2, null ,'m2', null,'s2' from dual
)
select id, coltype, col, subcoltype, subcol from TABLE1
UNPIVOT ((col, subcol) FOR (coltype, subcoltype) IN ((col1, subcol1) AS ('col1', 'subcol1'), (col2, subcol2) AS ('col2', 'subcol2')));
结果:
ID COLTYPE COL SUBCOLTYPE SUBCOL
---------- ---------------- -------- ---------------------------- --------
1 col1 m1 subcol1 s1
2 col2 m2 subcol2 s2