【问题标题】:How to use rollup/cube in pivot table (SUMMARIZE ROWS)如何在数据透视表中使用汇总/多维数据集(汇总行)
【发布时间】:2021-12-11 16:47:48
【问题描述】:

这是我的示例数据:

db<>fiddle

这是我的查询:

select * from (
select
    typ,
    user_name,
    sort,
    count_pc,
    weight    

from stat where typ=1 and dat>=trunc(sysdate)

)
pivot
(SUM(to_number(count_pc)) as pc, SUM(to_number(round(weight,0))) as hm
for sort in ('Alcohol','Food','NotFood' ,'Cigarette' ) )    

order by user_name asc
TYP USER_NAME 'Alcohol'_PC 'Alcohol'_HM 'Food'_PC 'Food'_HM 'NotFood'_PC 'NotFood'_HM 'Cigarette'_PC 'Cigarette'_HM
1 XX 24 630 24 630 null null null null
1 XY 64 1130 null null null null 38 1130
1 XZ null null null null 128 5130 null null

但我想要一个 sum_pcsum_weight 在表的和表中(多一行——在本例中为 2)。哪个用户总共有多少台电脑和体重....

期望的输出——黄色:

【问题讨论】:

  • 最好知道所需的输出是什么。
  • @RobertoHernandez 已添加。

标签: sql oracle pivot rollup


【解决方案1】:

我认为你不需要使用任何rollup 函数。我很确定也许有更好、更优雅的解决方案,但要获得你想要的输出,你可以使用这个

提示:我必须使用子选择来摆脱来自枢轴的列名。

select 
b.* , 
coalesce(alcohol_pc,0)+coalesce(food_pc,0)+coalesce(notfood_pc,0)+coalesce(cigarette_pc,0) as sum_pc,
coalesce(alcohol_hm,0)+coalesce(food_hm,0)+coalesce(notfood_hm,0)+coalesce(cigarette_hm,0) as sum_hm
from 
(
select typ, 
       user_name,
       "'Alcohol'_PC" as alcohol_pc , 
       "'Alcohol'_HM" as alcohol_hm ,
       "'Food'_PC"    as food_pc ,
       "'Food'_HM"    AS food_hm , 
       "'NotFood'_PC" as notfood_pc ,
       "'NotFood'_HM" as notfood_hm ,
       "'Cigarette'_PC" as cigarette_pc ,
       "'Cigarette'_HM" as cigarette_hm 
from 
(
select
    typ,
    user_name,
    sort,
    count_pc,
    weight
from stat where typ=1 and dat>=trunc(sysdate)
)
pivot
(SUM(to_number(count_pc)) as pc, SUM(to_number(round(weight,0))) as hm
for sort in ('Alcohol','Food','NotFood' ,'Cigarette' ) )
order by user_name asc
) b

db<>fiddle

【讨论】:

    猜你喜欢
    • 2022-10-23
    • 2013-08-26
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2014-06-03
    • 2011-12-05
    • 1970-01-01
    • 2018-05-07
    相关资源
    最近更新 更多