0

I have a table (shown below) where I need to calculate percent of toys that have price lower than 10. How do I do it in sql?

toy price
a   9
b   12
c   15
d   5
CWeeks
  • 407
  • 1
  • 5
  • 15
  • 1
    This answer seems to help: https://stackoverflow.com/questions/12789396/how-to-get-multiple-counts-with-one-sql-query select count(*), sum(case when price <= 10 then 1 else 0 end) AS cheapProductCount from toys group by toys – Soccergods Sep 16 '21 at 20:07

3 Answers3

2

A simple method uses avg():

select avg( (price < 10)::int ) as ratio
from toys;

If you want a percentage between 0 and 100, then multiply by 100.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

To simply get the ratio as a percentage you can just do

select Sum(case when price<10 then 1.0 end)/Count(*) * 100 as PercentLessThanTen
from t 
Stu
  • 30,392
  • 6
  • 14
  • 33
0

This can also be written without case which might be useful if you need more categories

select sum(c1), sum(c2), sum(c1)*100/sum(c2) as 'ratio' from
(
  select count(*) as c1, 0 as c2 from t where price < 10
  union all
  select 0 as c1, count(*) as c2 from t c1
) counts
S.Roeper
  • 309
  • 2
  • 6