You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;

示例结果

categorycountpercentage_of_total
mobile phones30075%
televisions10025%

内容的提问来源于stack exchange,提问作者Sql-power_bi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:25:52