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
| region | day | amount |
|---|---|---|
| East | 2024-01-01 | 100 |
| East | 2024-01-02 | 50 |
| East | 2024-01-03 | 25 |
| West | 2024-01-01 | 200 |
| West | 2024-01-03 | 300 |
Expected output
| region | day | amount | running_total |
|---|---|---|---|
| East | 2024-01-01 | 100 | 100 |
| East | 2024-01-02 | 50 | 150 |
| East | 2024-01-03 | 25 | 175 |
| West | 2024-01-01 | 200 | 200 |
| West | 2024-01-03 | 300 | 500 |
Hints
Hint 1
F.sum("amount").over(w) turns an aggregate into a window function.Hint 2
With anorderBy in the window, the default frame is "unbounded preceding to current row" — exactly a running total.Hint 3
Don't forget the finalorderBy("region", "day").Learn the concepts
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- withColumn · 6 min read. Add or replace one column, and why calling it in a long loop slows Spark down.
- orderBy · 4 min read. Sort rows ascending or descending, control where nulls go, and know what a global sort costs.
PySpark functions you'll practise
- Window spec
- sum
- withColumn
- orderBy
Related problems
- Latest Order per Customer · Medium · Window Functions, Filtering & Selection
- Top Two Salary Levels per Department · Medium · Window Functions, Filtering & Selection
- Month-over-Month Change · Medium · Window Functions
- 7-Day Moving Average · Medium · Window Functions
- Share of Category Total · Medium · Window Functions
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