avg_merge
avg_merge combines average states and returns the final mean. Each state's contribution is weighted by its admitted row count.
Averaging the batch means themselves would give the wrong result when batch sizes differ.
Prepare unequal batches
sql
CREATE TABLE readings(batch UInt8, value Int64);
INSERT INTO readings VALUES (1, 10), (1, 20), (2, 90);
CREATE TABLE partials(batch UInt8, state AggregateFunction(avg, Int64));
INSERT INTO partials
SELECT batch, avg_state(value)
FROM readings
GROUP BY batch;The batch means are 15 and 90, with two and one observations respectively.
Merge the states
sql
SELECT avg_merge(state) AS overall_average
FROM partials
FORMAT csv;text
40.0The result is (10 + 20 + 90) / 3, rather than (15 + 90) / 2.
Use avg_merge_state when another aggregation stage needs the combined state instead of its final value. See AggregateFunction for signatures and empty-state behavior.