Skip to content

40. Running Total by Region

Difficulty: Medium · Topics: Window Functions

For every row in sales, compute running_total: the cumulative sum of amount within the same region, ordered by day.

Return region, day, amount, running_total ordered by region then day. Null amounts should not add anything to the total.

Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

sales

regiondayamount
East2024-01-01100
East2024-01-0250
East2024-01-0325
West2024-01-01200
West2024-01-03300

Expected output

regiondayamountrunning_total
East2024-01-01100100
East2024-01-0250150
East2024-01-0325175
West2024-01-01200200
West2024-01-03300500

Hints

Hint 1F.sum("amount").over(w) turns an aggregate into a window function.
Hint 2With an orderBy in the window, the default frame is "unbounded preceding to current row" — exactly a running total.
Hint 3Don't forget the final orderBy("region", "day").

Learn the concepts

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 · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance

Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice