将垂直输入数据转换为Oracle中的水平输出

时间:2014-11-16 12:56:58

标签: sql oracle

我需要将行转换为Oracle中的列。我是这种格式的数据:

Apple Orange Mango Banana
15    20     12    67

所需的结果是:

Fruit      Number
Apple      15
Orange     20
Mango      12
Banana     67

我使用Union来获得此结果,但这不是通用的。

SELECT ‘Apple’ AS Fruit, Apple AS Number FROM fruits_tbl UNION
SELECT ‘Orange’, Orange FROM fruits_tbl UNION
SELECT ‘Mango’, Mango FROM fruits_tbl UNION
SELECT ‘Banana’, Banana FROM fruits_tbl;

我想要标准程序来获得建议的输出。

更新:想出Pivot是正确的做法!

1 个答案:

答案 0 :(得分:1)

由于Oracle 11g(tab是您的表名):

select * from tab 
UNPIVOT (num for fruit in (apple as 'apple', orange as 'orange', mango as 'mango', banana as 'banana'));

Oracle 10g:

with col_names as (
select 'apple' fruit from dual
union all select 'orange' from dual
union all select 'mango' from dual
union all select 'banana' from dual
)
select c.fruit, 
       case c.fruit       
          when  'apple' then t.apple          
          when  'orange' then t.orange          
          when  'mango' then t.mango          
          when  'banana' then t.banana          
       end as num
from tab t
cross join col_names c;