Skip to content
Advertisement

SQL how to find the product group with highest porportion of expensive items

I have a table with products, product_group and price level. How can I find the product group with the highest porportion of expensive items?

product | product_group | price_level
1             a              expensive
2             a              low
3             b              low
4             b              expensive
5             b              expensive
6             c              expensive

I have tried this query, but it keeps all price_levels, not just the expensive ones.

select product, product_group, price_level, 
    count(price_level) over (partition by product_group, price_level) as pl,
    count(product) over (partition by product_group) as p
from tbl

Essentially, I want to divide the number of expensive items in one product group by the total number of items in the same product group.

Desired output:

Product group | Percentage
     c              1

Advertisement

Answer

You can use conditional aggregation:

select product_group,
       avg( (price_level = 'expensive')::int ) as expensive_ratio
from tbl
group by product_group
order by expensive_ratio desc
limit 1;

The use of avg() is a convenient way to get the ratio you want. A more verbose method would be:

count(*) filter (where price_level = 'expensive') * 1.0 / count(*)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement