Merge unchanged versions in a type 2 history
The task
dim_customers_history has one row per version of a customer, but some versions changed only a column we do not track. When a version has the same tier and region as the version right before it, the two should be merged into one.
Return the merged history: one row for each run of consecutive versions of a customer that share tier and region, with:
customer_id,tierandregionvalid_from: thevalid_fromof the first version in the runvalid_to: thevalid_toof the last version in the run,NULLwhen that version is still open
Only versions that are next to each other are merged. If a customer goes back to an earlier tier later, that is a new run. Sort by customer_id, then valid_from.
Expected output
customer_idtierregionvalid_fromvalid_to- Sorted by customer_id ascending, then valid_from ascending.
- Checked on the sample and on 2 hidden datasets. How grading works
Tables Analytics warehouse · click a name to insert it
stg_orders669 rows in the sample
Raw order rows as loaded from the source. The same order can arrive several times: each change in the source sends a new copy, and some loads repeat a copy exactly.
| int | Order id from the source. | |
| int | Customer id. | |
| numeric(10,2) | Order total in the order currency. | |
| text | USD, EUR or GBP. | |
| text | placed, shipped, delivered or cancelled. | |
| timestamp | When the source last changed this order (UTC). | |
| timestamp | When our pipeline loaded this copy (UTC). |
dim_customers_history120 rows in the sample
Type 2 history: one row per version of a customer. A version is valid from valid_from up to, not including, valid_to. Key: customer_id, valid_from.
| int | Customer id. | |
| text | Name. | |
| text | bronze, silver or gold. | |
| text | EMEA, AMER or APAC. | |
| timestamp | Start of this version (UTC). | |
| timestamp | End of this version (not included). NULL for the current version. |
fx_rates254 rows in the sample
Closing exchange rates on business days only (no weekend rows). Key: rate_date, currency.
| date | Business day. | |
| text | EUR or GBP. | |
| numeric(12,6) | US dollars for one unit of the currency. |
inventory_snapshots336 rows in the sample
Stock on hand per product at the end of each day. A product missing from a day had no snapshot taken. Key: snapshot_date, sku.
| date | Day of the snapshot. | |
| text | Product code. | |
| int | Units in stock. |
Related questions
- Turn stock snapshots into restock eventsmedium
- Campaign by day fact table with cumulative spendhard
- Current gold customers by region from type 2 historyeasy
- Customer tier at a point in time from type 2 historymedium
- Daily end-of-day balance from transactions with a date spinehard
- Daily stock levels with a date spine and carry forwardhard
Loading the editor and PostgreSQL
Loading the editor and PostgreSQL