Skip to content

17. Subtotals with ROLLUP

Difficulty: Hard · Topics: Pivot, Unpivot & Rollup, Aggregations, Conditional Logic, Filtering & Selection

Finance wants one report with three levels of totals from the sales table: revenue per region and product, a subtotal per region, and a grand total.

Return region, product, total (sum of amount) and level, which is 'detail', 'region subtotal' or 'grand total'.

Careful: some sales have no product recorded (product is null). Those are still 'detail' rows; a null alone must not be mistaken for a subtotal.

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

sales

regionproductamount
NorthLaptop1200
NorthPhone800
NorthLaptop300
SouthPhone500
SouthTablet450

Expected output

regionproducttotallevel
NorthLaptop1500detail
NorthPhone800detail
SouthPhone500detail
SouthTablet450detail
Northnull2300region subtotal
Southnull950region subtotal
nullnull3250grand total

Hints

Hint 1df.rollup("region", "product") produces the (region, product), (region) and () groupings in one pass.
Hint 2In subtotal rows the rolled-up columns are null. F.grouping("product") returns 1 only when the null comes from the rollup, not from the data.
Hint 3Compute grouping() inside .agg(...), then build level with F.when.

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems