SQL计算组的百分比

时间:2018-04-08 19:40:41

标签: sql join where

我有一个关于计算SQL中组的百分比的问题。

我有一张包含不同食物数据的表格。这是我第一次查询的解决方案:

ProductCategory     Total products in Category
Tee, Coffee         225
Cosmetics           492
Sweets              1805

查询:

select productCategory, count(*) as numberOfProducts
from products
group by productCategory
order by productCategory

我做了第二个查询,过滤掉了非生物产品,这就是我得到的:

ProductCategory     Bioproducts in Category
Tee, Coffee         120
Cosmetics           1
Sweets              161

查询:

select productCategory, count(*) as numberofProducts
from products
where bio = 'true'
group by productCategory
order by productCateogry

我想计算每个类别的生物产品数量百分比。因此,对于第一类,计算将是(120/225)* 100 = 53,33%

我尝试过这样的查询:

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

但我的错误价值。

我的SQL语句错了吗?有谁知道我如何计算每个类别的生物产品的百分比率?

2 个答案:

答案 0 :(得分:1)

您必须计算子查询中的总计数/类别

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

答案 1 :(得分:1)

您可以使用条件聚合:

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;

我认为这是解决问题的最简单方法。