使用数据透视函数合并 Oracle 中的列集
Use Pivot Function to Merge Column sets in Oracle
我有一个 table 格式如下:
id colA1 colB1 colA2 colB2
1 100 499 500 999
我需要以下格式,
id colA colB
1 100 499
1 500 999
我尝试使用unpivot
方法,但结果如下,
colA colB
100 499
100 999
500 499
500 999
已使用查询
select * from (select colA, colB from my_table
unpivot
(colA for ColNm1 in(
colA1,
colA2
))
unpivot
(colB for ColNm2 in(
colB1,
colB2
));
简单地做一个 UNION ALL
,第一个 select 与 A1 和 B1,第二个 select 与 A2 和 B2:
select id, colA1 as colA, colB1 as colB
from my_table
UNION ALL
select id, colA2 as colA, colB2 as colB
from my_table
您可以像这样使用单个逆轴来执行此操作:
WITH my_table AS (SELECT 1 ID, 100 cola1, 499 colb1, 500 cola2, 999 colb2 FROM dual UNION ALL
SELECT 2 ID, 85 cola1, 163 colb1, 29 cola2, 457 colb2 FROM dual)
select ID,
cola,
colb
from my_table
UNPIVOT ((cola, colb) FOR def_col IN ((cola1, colb1), (cola2, colb2)));
ID COLA COLB
---------- ---------- ----------
1 100 499
1 500 999
2 85 163
2 29 457
我有一个 table 格式如下:
id colA1 colB1 colA2 colB2
1 100 499 500 999
我需要以下格式,
id colA colB
1 100 499
1 500 999
我尝试使用unpivot
方法,但结果如下,
colA colB
100 499
100 999
500 499
500 999
已使用查询
select * from (select colA, colB from my_table
unpivot
(colA for ColNm1 in(
colA1,
colA2
))
unpivot
(colB for ColNm2 in(
colB1,
colB2
));
简单地做一个 UNION ALL
,第一个 select 与 A1 和 B1,第二个 select 与 A2 和 B2:
select id, colA1 as colA, colB1 as colB
from my_table
UNION ALL
select id, colA2 as colA, colB2 as colB
from my_table
您可以像这样使用单个逆轴来执行此操作:
WITH my_table AS (SELECT 1 ID, 100 cola1, 499 colb1, 500 cola2, 999 colb2 FROM dual UNION ALL
SELECT 2 ID, 85 cola1, 163 colb1, 29 cola2, 457 colb2 FROM dual)
select ID,
cola,
colb
from my_table
UNPIVOT ((cola, colb) FOR def_col IN ((cola1, colb1), (cola2, colb2)));
ID COLA COLB
---------- ---------- ----------
1 100 499
1 500 999
2 85 163
2 29 457