> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How to aggregate data into several time buckets with a single materialized view

> Use ARRAY JOIN in one materialized view to write 5-minute, hourly and daily aggregates into a single AggregatingMergeTree table, and check them against the source table.

You do not need one materialized view and one target table per bucket size, or a chain of cascading views. A single materialized view can multiply every inserted row with `ARRAY JOIN`, once per bucket size, and write all the buckets into one [`AggregatingMergeTree`](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/aggregatingmergetree) table whose sorting key starts with the bucket size.

## Create the tables and the view

```sql theme={null}
CREATE TABLE requests
(
    ts DateTime('UTC'),
    duration_ms UInt32
)
ENGINE = MergeTree
ORDER BY ts;

CREATE TABLE requests_by_bucket
(
    resolution Enum8('5 minutes' = 1, '1 hour' = 2, '1 day' = 3),
    bucket_start DateTime('UTC'),
    requests SimpleAggregateFunction(sum, UInt64),
    avg_duration_ms AggregateFunction(avg, UInt32)
)
ENGINE = AggregatingMergeTree
ORDER BY (resolution, bucket_start);

CREATE MATERIALIZED VIEW requests_by_bucket_mv TO requests_by_bucket AS
SELECT
    resolution,
    bucket_start,
    count() AS requests,
    avgState(duration_ms) AS avg_duration_ms
FROM requests
ARRAY JOIN
    ['5 minutes', '1 hour', '1 day'] AS resolution,
    [toStartOfFiveMinutes(ts), toStartOfHour(ts), toStartOfDay(ts)] AS bucket_start
GROUP BY
    resolution,
    bucket_start;
```

How it works:

* [`ARRAY JOIN`](https://clickhouse.com/docs/reference/statements/select/array-join) over two arrays of the same length walks them in parallel. Every source row becomes three rows, one per resolution, each with the start of its bucket.
* `GROUP BY resolution, bucket_start` then aggregates each bucket of each resolution.
* `avgState` stores an intermediate state instead of a final average, so that the buckets written by different inserts can be merged correctly. A count can be summed, so `SimpleAggregateFunction(sum, UInt64)` is enough for it.
* `ts` has an explicit time zone, because the bucket boundaries computed by `toStartOfDay` and `toStartOfHour` depend on the time zone of the column.

## Insert data and read one resolution

Insert two days of data, one request every ten seconds:

```sql theme={null}
INSERT INTO requests
SELECT
    toDateTime('2026-01-01 00:00:00', 'UTC') + number * 10 AS ts,
    50 + intDiv(number, 360) * 3 + number % 6 AS duration_ms
FROM numbers(17280);
```

Read a resolution by filtering on it and finishing the aggregation with [`-Merge`](https://clickhouse.com/docs/reference/functions/aggregate-functions/combinators#-merge) and `sum`. The filter on `resolution` and `bucket_start` uses the primary key of the target table:

```sql theme={null}
SELECT
    bucket_start,
    sum(requests) AS requests,
    avgMerge(avg_duration_ms) AS avg_duration_ms
FROM requests_by_bucket
WHERE resolution = '1 hour'
    AND bucket_start >= '2026-01-02 00:00:00'
    AND bucket_start < '2026-01-02 04:00:00'
GROUP BY bucket_start
ORDER BY bucket_start;
```

```text theme={null}
   ┌────────bucket_start─┬─requests─┬─avg_duration_ms─┐
1. │ 2026-01-02 00:00:00 │      360 │           124.5 │
2. │ 2026-01-02 01:00:00 │      360 │           127.5 │
3. │ 2026-01-02 02:00:00 │      360 │           130.5 │
4. │ 2026-01-02 03:00:00 │      360 │           133.5 │
   └─────────────────────┴──────────┴─────────────────┘
```

The same aggregation over the source table returns the same four rows:

```sql theme={null}
SELECT
    toStartOfHour(ts) AS bucket_start,
    count() AS requests,
    avg(duration_ms) AS avg_duration_ms
FROM requests
WHERE ts >= '2026-01-02 00:00:00'
    AND ts < '2026-01-02 04:00:00'
GROUP BY bucket_start
ORDER BY bucket_start;
```

## Get the latest bucket of every resolution

`LIMIT 1 BY` keeps the first row of each resolution, which is the most recent bucket of the day because of the descending order:

```sql theme={null}
SELECT
    resolution,
    bucket_start,
    sum(requests) AS requests,
    avgMerge(avg_duration_ms) AS avg_duration_ms
FROM requests_by_bucket
WHERE bucket_start >= '2026-01-02 00:00:00'
    AND bucket_start < '2026-01-03 00:00:00'
GROUP BY
    resolution,
    bucket_start
ORDER BY
    resolution ASC,
    bucket_start DESC
LIMIT 1 BY resolution;
```

```text theme={null}
   ┌─resolution─┬────────bucket_start─┬─requests─┬─avg_duration_ms─┐
1. │ 5 minutes  │ 2026-01-02 23:55:00 │       30 │           193.5 │
2. │ 1 hour     │ 2026-01-02 23:00:00 │      360 │           193.5 │
3. │ 1 day      │ 2026-01-02 00:00:00 │     8640 │             159 │
   └────────────┴─────────────────────┴──────────┴─────────────────┘
```

## Costs and limits

* The view aggregates every inserted row once per resolution, three times in this example.
* Each inserted block adds one row per resolution and bucket it touches to the target table, and `AggregatingMergeTree` combines the rows of the same bucket in the background. Until then a bucket can have several rows, which is why the queries above always use `GROUP BY` with `sum` and `avgMerge`.
* All resolutions share one table, one sorting key and one set of columns. If the bucket sizes need different ones, use [cascading materialized views](https://clickhouse.com/docs/concepts/features/materialized-views/cascading-materialized-views.md) with one target table per bucket size instead.

## Keep fine buckets for a shorter time

A single table can still expire each resolution separately, with a table [TTL](https://clickhouse.com/docs/reference/engines/table-engines/mergetree-family/mergetree.md#table_engine-mergetree-ttl) that has a condition per resolution:

```sql theme={null}
ALTER TABLE requests_by_bucket
    MODIFY TTL
        bucket_start + INTERVAL 7 DAY DELETE WHERE resolution = '5 minutes',
        bucket_start + INTERVAL 90 DAY DELETE WHERE resolution = '1 hour';
```

`MODIFY TTL` changes the rule; existing parts are removed during later TTL merges. To apply the new rule to existing data immediately, materialize the TTL:

```sql theme={null}
ALTER TABLE requests_by_bucket MATERIALIZE TTL;
```

The example data is older than both limits, so after the TTL is materialized it keeps only the daily buckets.

## Related pages

* [Build a rollup with materialized views for fast time-series analytics](https://clickhouse.com/docs/guides/use-cases/real-time-analytics/time-series/materialized-view-rollup.md)
* [Incremental materialized views](https://clickhouse.com/docs/concepts/features/materialized-views/incremental-materialized-view.md)
