首页 > 解决方案 > mySQL 中各组之间总数的百分比

问题描述

我的表中有以下记录

ID Name Price
1  XYZ  100
2  XYZ  100
3  AAA  100
4  AAA  100
5  ABC  100
6  ABD  100

我想将单行条目分组到一个组中,将多行条目分组到另一组中。输出将只有 2 行 - 单次输入和多次输入,以及与总计相比,两个类别持有的价格百分比。

ABC 和 ABD 是单个条目,因为它们只有 1 行,而 XYZ 和 AAA 是多个条目,因为它们有 2 行。我想将多个条目和单个条目的所有价格列相加,然后计算百分比

输出:

Category         Percentage
Single_Entry     33.3%                ABC and ABD: (200/600*100)
Multiple_Entries 66.7%                XYZ and AAA: (400/600*100)

如何在 mySQL 中实现这一点。

标签: mysqlsqlcountsumwindow-functions

解决方案


我认为这是两个级别的聚合:

select (case when cnt = 1 then 'single' else 'multiple' end) as entry_type,
       sum(price) / sum(sum(price)) over() as ratio
from (select category, count(*) as cnt, sum(price) as price
      from t
      group by category
     ) c
group by entry_type;

推荐阅读