Subtotals

Learn how to include subtotals in aggregate queries.

Overview

Another useful technique to analyze data is producing subtotals. Let’s add multiple aggregation levels in the same query.

Consider this query that counts the number of employees in each department and role:

Press + to interact
SELECT
role,
department,
COUNT(*) as employees
FROM
emp
GROUP BY
role,
department;

This query is helpful in answering questions like how many developers are in the R&D department, or how many managers are in the Sales department. However, if we want to get the number of employees in the R&D department across all roles, this query is not very useful. We would have to manually sum the rows from the results, or write another query to answer this specific question.

The ROLLUP query

If we want to include the number of employees in each department across all roles, we need the results at a higher level than the query currently provides. The query aggregates combinations of department and role, but we want aggregates at the role level alone. For example, to get the ...

Access this course and 1400+ top-rated courses and projects.