# avg_state

`avg_state` returns an intermediate average state. It retains a total and count rather than only the average, so a later merge can combine batches with the correct weights.

## Create typed state storage

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

## Store one state per batch

```sql
INSERT INTO partials
SELECT batch, avg_state(value)
FROM readings
GROUP BY batch;
```

## Read a state's value

`finalize_aggregation` reads a single state's result:

```sql
SELECT batch, finalize_aggregation(state) AS average_value
FROM partials
ORDER BY batch
FORMAT csv;
```

```text
1,15.0
2,90.0
```

Use [`avg_merge`](https://coordinatordb.com/docs/guides/clickhouse/examples/aggregate-function-combinators/avg-merge) to combine several states. State function names and argument types must match the storage declaration exactly; CoordinatorDB states are not compatible with ClickHouse state bytes.
