使用Pivot函数合并Oracle中的列集

时间:2017-01-13 11:22:54

标签: sql oracle pivot unpivot

我有一个以下格式的表格:

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
));

2 个答案:

答案 0 :(得分:2)

你可以使用像这样的单个插件来执行此操作:

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

答案 1 :(得分:1)

只需选择UNION ALL,首先选择A1和B1,然后选择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