52. Build an SCD Type 2 History
Difficulty: Hard · Topics: Window Functions, Null Handling, Filtering & Selection
customer_updates is a change log: every time a customer's record was saved, a row with their city and updated_at. Saves often repeat the same city.
Build a Slowly Changing Dimension Type 2 table: one row per actual change of city, with valid_from (when it took effect), valid_to (when the next change took effect, null for the current row) and is_current.
Return customer_id, city, valid_from, valid_to, is_current.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
customer_updates
| customer_id | city | updated_at |
|---|---|---|
| 1 | Pune | 2024-01-01 |
| 1 | Pune | 2024-02-01 |
| 1 | Delhi | 2024-03-01 |
| 2 | Goa | 2024-01-15 |
Expected output
| customer_id | city | valid_from | valid_to | is_current |
|---|---|---|---|---|
| 1 | Pune | 2024-01-01 | 2024-03-01 | false |
| 1 | Delhi | 2024-03-01 | null | true |
| 2 | Goa | 2024-01-15 | null | true |
Hints
Hint 1
First drop saves that didn't change the city: compare withF.lag("city") per customer ordered by updated_at.Hint 2
On the remaining rows,F.lead("updated_at") is the end of each version.Hint 3
is_current is simply "valid_to is null".Learn the concepts
- Slowly changing dimensions (SCD Type 2) · 8 min read. Keep the full history of a dimension with one MERGE per batch, and the edge cases that break it.
- MERGE INTO and upserts · 7 min read. Matched, not-matched and not-matched-by-source clauses, step by step, and the duplicate-source error.
- lag / lead · 4 min read. Read the previous or next row in a window to compute changes, gaps and streaks.
PySpark functions you'll practise
- Lag
- Lead
- Window spec
- isNull
- filter
- select
- withColumn
- orderBy
Related problems
- Sessionize a Clickstream · Hard · Window Functions, Dates, Null Handling, Conditional Logic, Filtering & Selection
- Three-Day Login Streak · Hard · Window Functions, Aggregations, Dates, Filtering & Selection
- Trailing 3 Calendar Days (Range Frame) · Hard · Window Functions, Dates, Filtering & Selection
- Upsert: Merge New Records into a Table · Hard · Window Functions, Filtering & Selection
- Forward-Fill Missing Readings · Hard · 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