GROUP BY ROLLUP
GROUP BY ROLLUP is a SQL statement in the Aggregate Functions category. Generates subtotal rows at multiple grouping levels (col1+col2, col1, grand total). The syntax is SELECT col1, col2, SUM(value) FROM table GROUP BY ROLLUP(col1, col2);. It returns multi-level summary. A typical example: SELECT department, job_title, SUM(salary) AS total_salary FROM employees GROUP BY ROLLUP(department, job_title); -- Returns: -- IT, Developer, 500000 (detail) -- IT, Manager, 300000 (detail) -- IT, NULL, 800000 (subtotal by department) -- NULL, NULL, 1500000 (grand total) -- GROUPING() function identifies subtotal rows: SELECT CASE WHEN GROUPING(department)=1 THEN 'ALL' ELSE department END, ... A close relative is COUNT(), which returns the number of rows (or non-NULL values) in a group. A close relative is SUM(), which returns the sum of all non-NULL values in a group. Works with numeric columns. A close relative is AVG(), which returns the average (mean) of all non-NULL values in a group.