在Oracle行的多个列上使用pivot

Bad*_*dal 16 sql oracle pivot oracle11g

我在Oracle表(tab1)中有以下示例数据,我正在尝试将行转换为列.我知道如何在一列上使用Oracle pivot.但是可以将它应用于多个列吗?

样本数据:

Type  weight  height  
A     50      10  
A     60      12  
B     40      8  
C     30      15  
Run Code Online (Sandbox Code Playgroud)

我的预期输出:

A-count B-count C-count A-weight B-weight C-weight A-height B-height C-height  
2       1       1       110      40       30       22       8        15  
Run Code Online (Sandbox Code Playgroud)

我可以做什么:

with T AS 
(select type, weight from tab1 )
select * from T
PIVOT (
count(type)
for type in (A, B, C, D,E,F)
)  
Run Code Online (Sandbox Code Playgroud)

以上查询给出了以下结果

A B C  
2 1 1  
Run Code Online (Sandbox Code Playgroud)

我可以count(*)sum(weight)或替换sum(height)高度或重量.我想要做的,但我不能做,是在一个查询中转动所有三个(计数,重量和高度).

可以用枢轴完成吗?

Ale*_*ole 26

文档所示,您可以拥有多个聚合函数子句.所以你可以这样做:

select * from (
  select * from tab1
)
pivot (
  count(type) as ct, sum(weight) as wt, sum(height) as ht
  for type in ('A' as A, 'B' as B, 'C' as C)
);

A_CT A_WT A_HT B_CT B_WT B_HT C_CT C_WT C_HT
---- ---- ---- ---- ---- ---- ---- ---- ----
   2  110   22    1   40    8    1   30   15 
Run Code Online (Sandbox Code Playgroud)

如果您希望按照显示的顺序显示列,则添加另一级子查询:

select a_ct, b_ct, c_ct, a_wt, b_wt, c_wt, a_ht, b_ht, c_ht
from (
  select * from (
    select * from tab1
  )
  pivot (
    count(type) as ct, sum(weight) as wt, sum(height) as ht
    for type in ('A' as A, 'B' as B, 'C' as C)
  )
);

A_CT B_CT C_CT A_WT B_WT C_WT A_HT B_HT C_HT
---- ---- ---- ---- ---- ---- ---- ---- ----
   2    1    1  110   40   30   22    8   15 
Run Code Online (Sandbox Code Playgroud)

SQL小提琴.


小智 5

第二种命名列的方法更好,可以解决更多问题。我有一个要求,我想汇总从 PIVOT 返回的数据,因此有了列名,我可以简单地添加 2 并在第三个中获得所需的结果 -

select a_ct, b_ct, c_ct, a_wt, b_wt, c_wt, a_ht, b_ht, c_ht, a_wt + b_wt + c_wt tot_wt
from (
  select * from (
    select * from tab1
  )
  pivot (
    count(type) as ct, sum(weight) as wt, sum(height) as ht
    for type in ('A' as A, 'B' as B, 'C' as C)
  )
);

A_CT B_CT C_CT A_WT B_WT C_WT A_HT B_HT C_HT TOT_WT
---- ---- ---- ---- ---- ---- ---- ---- ---- ------
   2    1    1  110   40   30   22    8   15 180
Run Code Online (Sandbox Code Playgroud)

请注意,如果使用的 PIVOT 列之一返回 null,聚合函数(如 sum)将不会按预期运行,在这种情况下,我已使用 CASE 语句来解决它。

希望它能帮助某人。