Skip to main content
Yes. WITH CUBE, WITH ROLLUP and GROUPING SETS work in the SELECT of an incremental materialized view. The view computes the subtotals of every inserted block and writes them to the target table next to the detail rows. Two things make the result usable: a target table that merges the rows of different inserts, and a column that stores the grouping level, so that subtotal rows cannot be confused with detail rows.

Example

The target table is an AggregatingMergeTree table, and the result of the GROUPING function is the first column of its sorting key:
The view aggregates each INSERT separately, so the target table holds several rows with the same key until background merges combine them. Aggregate again when you read it:
grouping(country, device) returns a bit mask with one bit per argument, set when that key is aggregated away: 0 marks the detail rows, 1 the totals per country, 2 the totals per device and 3 the grand total. To read one level, filter on it, for example WHERE grouping_id = 1 for the totals per country.

Why the grouping column is needed

In a subtotal row, a key that is not part of the grouping set has the default value of its type: an empty string here, 0 for a number. A subtotal row therefore looks the same as a detail row whose key is really empty or zero. The example has such a row, a visit with an empty country. Without grouping_id, rows 1 and 9 of the result have the same key ('', 'mobile'), and so do rows 5 and 10. AggregatingMergeTree adds up rows with the same sorting key, so a target table ordered by (country, device) alone returns 225 hits for ('', 'mobile') and 265 hits for ('', ''). Neither number is a detail value or a subtotal.

Store fewer levels

CUBE computes every combination of the keys, so each additional key doubles the number of grouping sets that every insert computes and stores. To store fewer levels, replace WITH CUBE with WITH ROLLUP, or list the levels you need, for example GROUP BY GROUPING SETS ((country, device), (device), ()).

Alternative: NULL in subtotal rows

With the setting group_by_use_nulls, the keys of subtotal rows are NULL instead of default values. To use it in a materialized view:
  • add SETTINGS group_by_use_nulls = 1 at the end of the SELECT of the view;
  • declare the key columns of the target table as Nullable, for example LowCardinality(Nullable(String));
  • create the target table with the MergeTree setting allow_nullable_key = 1, because its sorting key then contains Nullable columns.