【发布时间】:2018-04-08 19:40:40
【问题描述】:
我有一个关于在 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 语句错了吗?有谁知道我如何计算每个类别的生物产品的百分比?
【问题讨论】: