【问题标题】:Oracle SQL group by rollup and ratio_to_reportOracle SQL group by rollup 和 ratio_to_report
【发布时间】:2020-09-25 14:19:13
【问题描述】:

我有一张这样的桌子

我有一个查询显示每个地区生产的车辆数量和该地区生产的车辆百分比

 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;

这给了我以下结果

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

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

【问题讨论】:

标签: sql oracle percentage rollup


【解决方案1】:

我更喜欢显式计算。您可以调整聚合行的计算(无论哪种方式):

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 是一个小数据库小提琴。

【讨论】:

  • 非常感谢。真的很感激。我觉得我在这里学到了很多新东西。
猜你喜欢
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多