# AggregateFunction

`AggregateFunction` stores an intermediate aggregate state. It retains enough information to combine several batches and calculate a final result later.

For example, an average state includes both a total and a count. Merging the states gives the average over all contributing rows, even when batches have different sizes.

## Syntax

```text
AggregateFunction(function, argument_type, ...)
```

* `function` — One of `sum`, `count`, `avg`, `min` or `max`.
* `argument_type` — The aggregate's declared input type. Count accepts zero or one argument type; the other functions require one.

## Usage

Use the function's `_state` variant to create a state. Use `_merge` to combine state rows and return a final value, or `_merge_state` to return another state. `finalize_aggregation` reads the result of a single state.

States must have exactly matching function names and argument types. Their native representation is specific to CoordinatorDB and is not compatible with ClickHouse aggregate-state bytes. Finalize a state before using its value in ordinary arithmetic or numeric aggregates.

## Usage Example

### Storing partial averages

```sql
CREATE TABLE measurements(batch UInt8, value Int64);
INSERT INTO measurements VALUES (1, 10), (1, 20), (2, 90);

CREATE TABLE partials(batch UInt8, result AggregateFunction(avg, Int64));
INSERT INTO partials
SELECT batch, avg_state(value)
FROM measurements
GROUP BY batch;
```

Read individual state results:

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

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

Merge them to obtain the average of all observations:

```sql
SELECT avg_merge(result)
FROM partials
FORMAT csv;
```

```text
40.0
```

## Empty states

A count or sum state finalizes to zero when no values contribute. Minimum and maximum states finalize to the argument type's default; an average state finalizes to `NULL`.

These rules differ from ordinary `sum`, `min` and `max` on empty input. See [aggregate combinators](https://coordinatordb.com/docs/reference/functions/aggregate-functions/combinators) for the complete variant list and [SimpleAggregateFunction](https://coordinatordb.com/docs/reference/data-types/simpleaggregatefunction) for directly readable scalar partial results.
