Weighted Average Per Group

Compute a weighted average as SUM(value * weight) over SUM(weight), because averaging already-averaged group values weights small samples the same as big ones.

SqlData Integrity

Code

snippet
-- 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;

What the code does

Several statements share this file — SELECT, with endpoint_stats among the objects involved.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; SUM, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run it in the endpoint_stats database context.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `endpoint_stats`.