I have a table like this
I have a query to show the number of vehicles manufactured in each region and the percentage of vehicles manufactured in the region
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;
which gives me the following result
But I want something like this, which exclude the total when calculating the percentage.
Is it possible to achieve it with ratio_to_report? If not, how could I alter the query?
I prefer an explicit calculation. You can adjust the calculation (either way) for the aggregated row:
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 . . .
The same idea doesn't quite work with ratio_to_report()
-- because it returns NULL
instead of 1. But you could use:
coalesce(round(ratio_to_report(case when grouping_id(region) = 0 then count(*) end) over(), 2), 1) as rr
Here is a little db<>fiddle.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.