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.

SqlData Integrity

Code

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

FAQ

Which tables does this file reference?
`readings`.