SQL汇总汇总和比率到报告

问题描述 投票:0回答:1

我有这样的桌子

enter image description here

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

 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;

给我以下结果

enter image description here

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

enter image description here

是否可以通过ratio_to_report实现它?如果没有,我该如何更改查询?

sql oracle percentage rollup
1个回答
0
投票

我希望进行显式计算。您可以调整汇总行的计算(任一种方式):

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

[Here是一点db <>小提琴。

© www.soinside.com 2019 - 2024. All rights reserved.