rollup / cube
Subtotals and grand totals in one pass, and how grouping() tells a total row from a real null.
Step 1 · PySpark functions · Gold · Gold reshaping patterns, lesson 1 of 3
On this page
Read first: groupBy + agg (skip if you know it)
In plain words first
A shop's sales sheet lists each product per month, then a subtotal for each month, then one grand total at the bottom. Writing it by hand you add up the same numbers three times at different levels.
rollup writes all three levels in one go. cube also adds the totals the other way round, for example per product across all months.
Unlock the full lesson
You have read the free part. The rest of this advanced lesson:
- What it does
- Step by step
- Run the example
- Real nulls vs total rows
- GROUPING SETS in SQL
- Under the hood
- Common mistakes
- Key takeaways
- Interview prep with 3 follow-up questions
- Check yourself: 3 questions
Unlock it with the Complete pass (every advanced problem and lesson) or on its own.
Practise this
Problems that use rollup / cube, graded on hidden tests
Keep going
Up next · Gold reshaping patterns · lesson 2 of 3 · 3 min readunpivot
Turn columns into rows (wide to long) with unpivot or the SQL stack() function.
Related lessons
Previous: Gaps and islands
Primary sources: DataFrame.rollup · DataFrame.cube · GROUP BY (SQL)