mysql - 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 中实现这一点。
解决方案
我认为这是两个级别的聚合:
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;
推荐阅读
- python - 我的列表理解中的“for”循环的语法有什么问题吗?
- android - 导航片段显示在导航架构组件jetpack中的上一个片段后面
- excel - 如何处理Excel工作表中的数据更改事件以刷新所有数据透视表?
- minecraft-forge - minecraft forge - 我如何获得一个实体并改变它的状态?
- powerpoint - 使用 pandoc 或其他东西从 slidy 转换为 powerpoint?
- python - 寻找始终高于平均水平的患者
- html - 它不会将我的网站及其模板呈现到 localhost1313
- c# - 单个字段值不会在缓存更新时更新
- corda - 如何用corda设计一个开放的市场
- python - 与多个 MultiPolygons 的形状相交,其中一定比例的 Multipolygons 相交?