如何在Oracle SQL输出中将行转换为表列?

时间:2019-04-16 03:41:53

标签: sql oracle pivot oracle12c

我想将oracle sql输出转换为表数据行转换为Column。

我的SQL输出

ITEM    | RESULT
-----------------
Shell   | 296.5
-----------------
Shell   | 299.8
-----------------
Shell   | 311
-----------------
Shell   | 289
-----------------
Lining  | 301.33
-----------------
Lining  | 296.5
-----------------
Lining  | 299
-----------------

但是我想要类似-

的输出
Shell    |   Lining
----------------------
296.5    |  301.33
----------------------
299.8    |  296.5
----------------------
311      |  299
----------------------
289      |  0 -- 

如果任何项目的结果较少,则将填充零(0)

因此,请向我建议将满足我要求的sql代码。 谢谢

4 个答案:

答案 0 :(得分:0)

PIVOT是您所需要的。 在这里看看: https://www.techonthenet.com/oracle/pivot.php

答案 1 :(得分:0)

您可以使用条件聚合

select max(case when ITEM='Shell' then RESULT end) as shell,
max(case when ITEM='Lining' then RESULT end) as Lining
from 
  ( select *,row_number() over(partition by item order by result) rn from 
    tablename
  )A
group by rn

答案 2 :(得分:0)

您需要进行透视,如下所示。但是,您需要枢纽的聚合功能。您需要从表格中再选择一列进行分组。

SELECT * FROM 
(SELECT Item, Result
FROM Table1) 
PIVOT
(
  SUM(Result) FOR ITEM IN ('SHELL' Shell,'LINING' Lining) 
)

答案 3 :(得分:0)

您可以使用行号进行数据透视,以便在使用max时不会丢失分组中的任何值。

with cte as (
select 'Shell' as Item,   '296.5'  as Resultn from dual  union all 
select 'Shell' as Item,   '299.8'  as Resultn from dual  union all 
select 'Shell' as Item,   '311'    as Resultn from dual  union all 
select 'Shell' as Item,   '289'    as Resultn from dual  union all 
select 'Lining' as Item,  '301.33' as Resultn from dual  union all 
select 'Lining' as Item,  '296.5'  as Resultn from dual  union all 
select 'Lining' as Item,  '299'    as Resultn from dual   )

select nvl(Shell,0) Shell, nvl(Lining,0) Lining from (
select  c.item, c.Resultn, row_number() over (partition by Item order by Resultn) rownumn   
from cte c 
) z 
pivot 
(
max(Resultn) 
for item in ('Shell' as Shell  ,'Lining' as Lining ));

输出:

SHELL   LINING
289     296.5
296.5   299
311      0
299.8   301.33