【问题标题】:SQL calculating percentage of a groupSQL计算组的百分比
【发布时间】: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 语句错了吗?有谁知道我如何计算每个类别的生物产品的百分比?

【问题讨论】:

    标签: sql join where


    【解决方案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;
    

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

    【讨论】:

    • 从查询编写的角度来看,这看起来很简单,但在性能方面似乎会得到一个可笑的低效答案。下面提到的子查询方法不是会返回更高效的答案吗?
    • @DylanB 。 . .不知何故,您认为两个聚合和一个连接会比单个聚合更高效?我不太确定如何帮助你解决这个问题。这应该是表达逻辑的最有效方式。
    • 您正在创建一个任意数值,然后对其进行平均。我认为聚合这些值然后在整体上进行数学总计会比这更有效,但也许你是对的......如果以正确的方式设置表上的索引,则执行某些版本的 SQL存储常见的元值,如平均值和总和?如果他们这样做了,使用现有结构而不是动态创建一个神奇的变量将是一个更清洁、更有效的解决方案。
    • @DylanBrams 。 . .您对查询中的昂贵和廉价性能没有很好的了解。一般来说,任何处理数据的东西都会比任何在单行上进行算术的东西更昂贵。 (也有例外,但这并不算是其中之一。)
    • 您正在内存中生成一个整数并对其进行算术运算,而不是使用两个索引信息计数。从基本算法的角度来看,无论如何您都需要收集计数信息,但您不需要为额外的整数保留内存并对其进行所有数学运算。您实际上是在建立一个运行平均值,计数只是计算可能已经被索引的东西。奇怪的是,您认为这是单行算术;您正在为每一行生成额外的数据,然后对其进行算术运算。我差点把这条评论标记为粗鲁。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      相关资源
      最近更新 更多