# avg_merge_state

`avg_merge_state` merges average states and returns another state. Use it when a calculation has several stages, such as combining per-batch states before combining them across a larger period.

## Create batch states

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

## Retain the combined state

```sql
CREATE TABLE combined(state AggregateFunction(avg, Int64));
INSERT INTO combined SELECT avg_merge_state(state) FROM partials;
```

## Finalize at the boundary

```sql
SELECT finalize_aggregation(state)
FROM combined
FORMAT csv;
```

```text
40.0
```

The merged state still retains the contribution count needed by another `avg_merge` or `avg_merge_state`. Finalizing a state reads it without combining other rows.

See [`avg_state`](https://coordinatordb.com/docs/guides/clickhouse/examples/aggregate-function-combinators/avg-state), [`avg_merge`](https://coordinatordb.com/docs/guides/clickhouse/examples/aggregate-function-combinators/avg-merge) and [aggregate combinators](https://coordinatordb.com/docs/reference/functions/aggregate-functions/combinators).
