Reputation: 33
I have got a question about calculating the percentage of groups in SQL.
I have a table with different food data. This is the solution I got for my first query:
ProductCategory Total products in Category
Tee, Coffee 225
Cosmetics 492
Sweets 1805
Query:
select productCategory, count(*) as numberOfProducts
from products
group by productCategory
order by productCategory
I did a second query filtering out the non-bio products and this is what I got:
ProductCategory Bioproducts in Category
Tee, Coffee 120
Cosmetics 1
Sweets 161
Query:
select productCategory, count(*) as numberofProducts
from products
where bio = 'true'
group by productCategory
order by productCateogry
I want to calculate the amount of bio-products in percent for each category. So for the first category the calculation would be (120/225) * 100 = 53,33 %
I tried doing this query:
select productCategory, round(count(*)
/ (
select count(*) as numberofProducts
from products) * 100, 2) || ' %' as percentageBio
from products
where bio = 'true'
group by productCategory
order by productCategory
but I am getting wrong values.
Is my SQL statement wrong? Does anyone know how I can calculate the percentage rate of bio products for each category?
Upvotes: 1
Views: 6301
Reputation: 1269873
You can use conditional aggregation:
select productCategory, count(*) as numberofProducts,
avg(case when bio = 'true' then 100.0 else 0 end) as percentage
from products
group by productCategory
order by productCategory;
I think this is the simplest way to solve the problem.
Upvotes: 3
Reputation: 51973
You have to calculate total count / category in a subquery
SELECT productCategory, round(100 * count(*) / tot_count,2)
FROM (SELECT count(*) as tot_count, productCategory cat
FROM products
GROUP BY productCategory) AS sub,
products
WHERE bio = 1 and cat = productCategory
GROUP BY productCategory
ORDER BY productCategory
Upvotes: 2