表Oracle中的数据未显示数据

时间:2018-01-31 21:11:47

标签: sql oracle11g unpivot

我的来源就像

**Col1  Col2 Col3  Col4    Col5  Col6**
1     ABC  STAT1  STAT2  COM1  COM2

我如何到达

**Col1 Col2 type Col4   Col5**
1    ABC  STAT STAT1  STAT2
1    ABC  COM  COM1   COM2

我看了Unpivot,它能够做一个专栏 - >一排。但我正在寻找2列到1行。 Union all将是一个选项,但我希望看到它使用unpivot

1 个答案:

答案 0 :(得分:0)

我首选的方法是横向连接,但在Oracle 12c之前不可用。如果您只有两个选项且表格不是很大,union all可能就足够了:

select col1, col2, 'STAT' as type, col3 as col4, col4 as col5
from t
union all
select col1, col2, 'COM' as type, col5, col6
from t;

如果两次扫描表是性能问题,还有其他选项。

没有unpivot的一个非常简单的方法是join

select t.col1, t.col2, tt.type,
       (case when tt.type = 'STAT' then col3 else col5 end),
       (case when tt.type = 'STAT' then col4 else col6 end)
from t cross join
     (select 'STAT' as type from dual union all
      select 'COM' as type from dual
     ) tt;