← 中文资源

简体中文版本

按权重求组内平均

加权平均 = SUM(值×权重)/SUM(权重):把组均值直接 AVG 会给小样本与大样本同权,健康检查这类海量小值会严重拉低整体,NULLIF 兜住除零。

阅读英文原文

实现说明

实际执行的是 SELECT——endpoint_stats 是涉及的对象。 用到的 SQL 构件:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;用 SUM、AVG 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序。

常见问题

这里涉及哪些关系(表/CTE)?

引用的是 endpoint_stats。

核心语句

SELECT endpoint,
       SUM(avg_ms * calls) / NULLIF(SUM(calls), 0) AS merged_avg_ms
FROM endpoint_stats
GROUP BY endpoint
ORDER BY endpoint;

代码示例

-- Weighted average: SUM(value * weight) / SUM(weight)
-- The mistake is averaging the per-group means again: small and large samples get equal weight
WITH endpoint_stats (endpoint, calls, avg_ms) AS (
    VALUES
        ('GET /orders',  9000,  120.0),
        ('GET /orders',  1000,  180.0),
        ('POST /orders', 500,   340.0),
        ('GET /health',  99000, 4.0)
)
SELECT
    SUM(avg_ms * calls) / NULLIF(SUM(calls), 0) AS weighted_avg_ms,
    -- Contrast: the naive average gives the 4ms health check the same say as the 180ms heavy endpoint
    ROUND(AVG(avg_ms)::numeric, 2)              AS naive_avg_ms,
    SUM(calls)                                  AS total_calls
FROM endpoint_stats;

-- Two samples of one group merge into a single row with the same formula
SELECT endpoint,
       SUM(avg_ms * calls) / NULLIF(SUM(calls), 0) AS merged_avg_ms
FROM endpoint_stats
GROUP BY endpoint
ORDER BY endpoint;