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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which relations are involved here?
- The references are `endpoint_stats`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.