Átomo
50Ru
Agregação · SQL

ROLLUP / CUBE

Abrir na tabela

Definição

Geram subtotais e total geral no mesmo GROUP BY. ROLLUP segue a hierarquia das colunas; CUBE gera todas as combinações.

Exemplos

1. Subtotal por ano e total geral
SELECT year, month, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (year, month);
2. Todas as combinações
SELECT region, channel, SUM(amount) AS total
FROM sales
GROUP BY CUBE (region, channel);
3. Identificar as linhas de total
SELECT CASE WHEN GROUPING(region) = 1
            THEN 'TOTAL' ELSE region END AS region,
       SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (region);

No mesmo grupo