26. Year-over-Year Growth
Difficulty: Medium · Topics: Joins, Filtering & Selection
monthly_revenue has one row per (year, month). For every row, add prev_year_revenue (same month, previous calendar year) and yoy_pct = growth in percent, rounded to 1 decimal.
If there is no row for the same month last year, both are null. Note: some years are missing entirely. Return year, month, revenue, prev_year_revenue, yoy_pct.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
monthly_revenue
| year | month | revenue |
|---|---|---|
| 2022 | 1 | 100 |
| 2022 | 2 | 80 |
| 2023 | 1 | 150 |
| 2023 | 2 | 60 |
Expected output
| year | month | revenue | prev_year_revenue | yoy_pct |
|---|---|---|---|---|
| 2022 | 1 | 100 | null | null |
| 2022 | 2 | 80 | null | null |
| 2023 | 1 | 150 | 100 | 50 |
| 2023 | 2 | 60 | 80 | -25 |
Hints
Hint 1
lag over partitionBy("month").orderBy("year") returns the previous available year, which is wrong when a year is missing.Hint 2
Instead shift the table by one year (year + 1) and join it back on (year, month).Hint 3
A left join keeps rows that have no previous year.Learn the concepts
- join · 5 min read. Combine DataFrames on a key: inner, left, right and full joins, and the duplicate-key fan-out trap.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
- 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
- join
- select
- withColumn
Related problems
- Customers Without Orders · Medium · Joins, Filtering & Selection
- Employees and Their Departments · Medium · Joins, Filtering & Selection
- Employees Earning More than Their Manager · Medium · Joins, Filtering & Selection
- Joining on Nullable Keys · Medium · Joins, Null Handling, Filtering & Selection
- Fill Missing Dates (Calendar Spine) · Hard · Joins, Arrays, Aggregations, Dates, Null Handling, Filtering & Selection
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