Avg Skips Null Inputs In Its Denominator
AVG ignores NULL inputs, so its denominator is the non-null count rather than the row count; zero-fill with COALESCE only when that is the intent.
Code
-- AVG/SUM/MIN/MAX 只消费非 NULL 输入 (skips NULL inputs):分母不是行数
-- 分母 (denominator) 是 COUNT(value),与 COUNT(*) 的行数口径不同
WITH readings(sensor, value) AS (
VALUES
('a1', 20.5),
('a1', NULL), -- 掉线:没有读数,不是 0 度
('a2', 22.5),
('a2', NULL)
)
SELECT
sensor,
COUNT(*) AS row_count, -- 含 NULL:2
COUNT(value) AS counted_values, -- 非 NULL:1
AVG(value) AS avg_skips_nulls, -- 20.5 / 22.5,分母 = COUNT(value) = 1
AVG(COALESCE(value, 0)) AS avg_zero_filled -- 10.25 / 11.25:NULL 当 0 参与
FROM readings
GROUP BY sensor
ORDER BY sensor;Avg Skips Null Inputs In Its Denominator, line by line
At its core this is a single SELECT statement against readings.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, AVG aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Using it
Run the statement against the readings table.
Interactive Tools for This Topic
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.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.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 tables does this file reference?
- `readings`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.