oracle sql group by rollup和比率报告

ig9co6j1  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(363)

我有一张这样的table

我有一个查询,显示在每个地区制造的车辆数量和在该地区制造的车辆百分比

select  
            COALESCE(Region, 'Total') AS Region,
            count(veh_vin) as "Total Vehicles Manufactured",
            round(ratio_to_report(count(veh_vin)) over(),2) as rr
        from( 
            select 
                case 
                    when substr(veh_vin,1,1) between 'A' and 'C' then 'Africa'
                    when substr(veh_vin,1,1) between 'J' and 'R' then 'Asia' 
                    when substr(veh_vin,1,1) between 'S' and 'Z' then 'Europe'
                    when substr(veh_vin,1,1) between '1' and '5' then 'North America'
                    when substr(veh_vin,1,1) between '6' and '7' then 'Oceania'
                    when substr(veh_vin,1,1) between '8' and '9' then 'South America'
                    else 'Unknown'
                end as Region,
                veh_vin
            from vehicle
        )
        group by ROLLUP(Region)
        order by count(veh_vin), Region;

结果如下

但我想要这样的东西,在计算百分比时不包括总数。

有没有可能实现这一点的比率报告?如果没有,我如何修改查询?

66bbxpm5

66bbxpm51#

我喜欢显式计算。您可以调整聚合行的计算(任意一种方式):

select coalesce(Region, 'Total') AS Region,
       count(*) as "Total Vehicles Manufactured",
       round(count(*) * 1.0 / sum(case when grouping_id(region) = 0 then count(*) end) over (), 2) as rr
from . . .

同样的想法对我不太适用 ratio_to_report() --因为它回来了 NULL 而不是1。但你可以用:

coalesce(round(ratio_to_report(case when grouping_id(region) = 0 then count(*) end) over(), 2), 1) as rr

这是一把小小提琴。

相关问题