42. Month-over-Month Change
Difficulty: Medium · Topics: Window Functions
monthly_revenue has one row per month (format YYYY-MM).
Return month, revenue, prev_revenue, change where prev_revenue is the previous month's revenue and change = revenue - prev_revenue. The first month has nulls for both. Order the result by month.
Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
monthly_revenue
| month | revenue |
|---|---|
| 2024-01 | 1000 |
| 2024-02 | 1200 |
| 2024-03 | 900 |
| 2024-04 | 900 |
Expected output
| month | revenue | prev_revenue | change |
|---|---|---|---|
| 2024-01 | 1000 | null | null |
| 2024-02 | 1200 | 1000 | 200 |
| 2024-03 | 900 | 1200 | -300 |
| 2024-04 | 900 | 900 | 0 |
Hints
Hint 1
F.lag("revenue", 1).over(Window.orderBy("month")) reads the previous row.Hint 2
A window withoutpartitionBy treats the whole DataFrame as one partition.Learn the concepts
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- lag / lead · 4 min read. Read the previous or next row in a window to compute changes, gaps and streaks.
- withColumn · 6 min read. Add or replace one column, and why calling it in a long loop slows Spark down.
PySpark functions you'll practise
- Lag
- Window spec
- withColumn
- orderBy
Related problems
- Latest Order per Customer · Medium · Window Functions, Filtering & Selection
- Running Total by Region · Medium · Window Functions
- Top Two Salary Levels per Department · Medium · Window Functions, Filtering & Selection
- 7-Day Moving Average · Medium · Window Functions
- Customer Spend Quartiles (NTILE) · 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