Skip to content

34. 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_idcityupdated_at
1Pune2024-01-01
1Pune2024-02-01
1Delhi2024-03-01
2Goa2024-01-15

Expected output

customer_idcityvalid_fromvalid_tois_current
1Pune2024-01-012024-03-01false
1Delhi2024-03-01nulltrue
2Goa2024-01-15nulltrue

Hints

Hint 1First drop saves that didn't change the city: compare with F.lag("city") per customer ordered by updated_at.
Hint 2On the remaining rows, F.lead("updated_at") is the end of each version.
Hint 3is_current is simply "valid_to is null".

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

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems