Oracle SQL实现分组统计ID并计算各组占总数百分比
Oracle SQL 分组统计并计算占比的合并方案
你可以通过以下两种方式合并两个查询,同时得到分组统计结果和占比:
方法一:使用窗口函数(推荐,Oracle 12c+适用)
窗口函数可直接在分组查询中计算总数量,无需额外关联子查询:
SELECT category, COUNT(id) AS count, ROUND((COUNT(id) / SUM(COUNT(id)) OVER ()) * 100, 2) || '%' AS percentage_of_total FROM sales GROUP BY category ORDER BY count DESC;
SUM(COUNT(id)) OVER ():计算所有分组的id总数(即总数量)ROUND(..., 2):将百分比保留2位小数,可根据需求调整位数- 拼接
'%'符号将数值转换为百分比格式
方法二:使用CTE关联总数量
如果需要兼容旧版本Oracle,可先通过CTE获取总数量,再关联分组统计结果:
WITH total_sales AS ( SELECT COUNT(id) AS total_count FROM sales ) SELECT s.category, COUNT(s.id) AS count, ROUND((COUNT(s.id) / ts.total_count) * 100, 2) || '%' AS percentage_of_total FROM sales s CROSS JOIN total_sales ts GROUP BY s.category, ts.total_count ORDER BY count DESC;
示例结果
| category | count | percentage_of_total |
|---|---|---|
| mobile phones | 300 | 75% |
| televisions | 100 | 25% |
内容的提问来源于stack exchange,提问作者Sql-power_bi
相关产品推荐
相关产品推荐

