如何在数据透视 table 中使用 rollup/cube(汇总行)

How to use rollup/cube in pivot table (SUMMARIZE ROWS)

这是我的示例数据:

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 和 table (再排一排 - 在本例中为 2)。哪个用户总共有多少pc和weight....

期望输出 -- 黄色:

我认为您不需要使用任何 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