简体   繁体   中英

SQL calculating percentage of a group

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?

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM