task History, SCD & as-of · hard
Build a region history from snapshots
shopper_snapshots records each shopper's region at month end. Return shopper_id, region, valid_from and valid_to — one row per unbroken run of the same region.
what to return
- Columns
shopper_idregionvalid_fromvalid_toin this order- Rows
- 11 rows · any order
- Watch for
- valid_from is the run's first snapshot_date; valid_to is the first snapshot_date of the shopper's next run, or NULL for the latest run.
- A missing region (NULL) is its own value: consecutive NULL snapshots form one run.
- If a shopper returns to an earlier region later, that's a new run.
- Skill
- Compress snapshots into change history. Refresher: LEAD & the next event →
expected result
Your query should return exactly these columns and values. Run it and compare.
expected result11 rows · any order
| shopper_id | region | valid_from | valid_to |
|---|---|---|---|
| 1 | West | 2025-01-31 | 2025-04-30 |
| 1 | East | 2025-04-30 | NULL |
| 2 | East | 2025-01-31 | NULL |
first 3 of 11 rows
data you can query
Sample rows from each table. Each column shows its type underneath; → marks a link to another table.
shopper_snapshots3 columns · 20 rows
| snapshot_datetext · key | shopper_idinteger · key | regiontext |
|---|---|---|
| 2025-01-31 | 1 | West |
| 2025-02-28 | 1 | West |
| 2025-03-31 | 1 | West |
| 2025-04-30 | 1 | East |
| 2025-01-31 | 2 | East |
showing 5 of 20 rows
solution.sql
Hints and the answer are always available. Using them counts the question as solved with help.