Build a Type-2 SCD (slowly changing dimension) from daily snapshots: collapse consecutive snapshots with identical tier and region into one version, opening a new version when either changes. Return customer_key, tier, region, effective_from, effective_to and is_current.
Input Table(s)
customer_snapshots
| Column | Type | Meaning |
|---|
| snapshot_id | INT | Snapshot identifier |
| customer_key | INT | Customer the snapshot describes |
| snapshot_date | DATE | Day the snapshot was taken |
| tier | VARCHAR(20) | Customer tier on that day, not null |
| region | VARCHAR(20) | Customer region on that day, not null |
Keys: snapshot_id is the primary key. Each (customer_key, snapshot_date) pair is unique.
Output Contract
| Column | Meaning |
|---|
| customer_key | The customer |
| tier | Tier of this version |
| region | Region of this version |
| effective_from | snapshot_date on which the version first appeared |
| effective_to | snapshot_date on which the next version began, or NULL if this version is still active |
| is_current | 1 for each customer's latest version, else 0 |
Sort by customer_key ascending, then effective_from ascending. The pair (customer_key, effective_from) is unique. No rounding is involved.
Example
customer_snapshots
| snapshot_id | customer_key | snapshot_date | tier | region |
|---|
| 1 | 100 | 2024-01-01 | silver | east |
| 2 | 100 | 2024-01-02 | silver | east |
| 3 | 100 | 2024-01-03 | gold | east |
| 4 | 100 | 2024-01-04 | gold | west |
Expected output:
| customer_key | tier | region | effective_from | effective_to | is_current |
|---|
| 100 | silver | east | 2024-01-01 | 2024-01-03 | 0 |
| 100 | gold | east | 2024-01-03 | 2024-01-04 | 0 |
| 100 | gold | west | 2024-01-04 | NULL | 1 |
Customer 100 has 4 snapshots. Jan 1 and Jan 2 are identical (silver/east) and collapse into one version with effective_from 2024-01-01 and effective_to 2024-01-03. The gold/east version runs from Jan 3 to Jan 4, and the gold/west version opens on Jan 4 with effective_to NULL and is_current 1.
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
tier
and
region
are non-null strings, and
snapshot_date
values are valid dates.
-
effective_to
is an exclusive end: it equals the
effective_from
of the customer's next version, not the last day of this one.
-
Only consecutive snapshots collapse. If a customer goes silver, then gold, then back to silver, that is three versions.
-
Each snapshot is compared with the same customer's previous snapshot in date order, even when days are missing between them.