Skip to content

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

monthrevenue
2024-011000
2024-021200
2024-03900
2024-04900

Expected output

monthrevenueprev_revenuechange
2024-011000nullnull
2024-0212001000200
2024-039001200-300
2024-049009000

Hints

Hint 1F.lag("revenue", 1).over(Window.orderBy("month")) reads the previous row.
Hint 2A window without partitionBy treats the whole DataFrame as one partition.

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