runtime
47 / 139

task History, SCD & as-of · hard

Build a country history from invoices

For identified customers whose invoices list more than one country, return customer_id, country, valid_from and valid_to: one row per run of consecutive invoices (by ordered_at, order_id) with the same country. valid_from is the run’s first invoice date; valid_to is the next run’s first invoice date, NULL for the last run.

what to return

Columns
customer_idcountryvalid_fromvalid_to in this order
Rows
13 rows · any order
Skill
Turn event snapshots into validity intervals. Refresher: Compare rows with LAG →

expected result

Your query should return exactly these columns and values. Run it and compare.

expected result13 rows · any order
customer_idcountryvalid_fromvalid_to
12431Belgium2010-01-152010-03-04
12431Australia2010-03-042010-07-19
12431Belgium2010-07-192010-08-17

first 3 of 13 rows

data you can query

Retail dataset: the first 6 rows of each table. Under each column name: the kind of value it holds, and which table it links to. Your queries run on all rows.

orders6 columns · 6,722 rows
order_idnumber · unique idinvoice_notextcustomer_idnumber · links to customersordered_atdate & timecountrytextorder_typetext
1489438181022009-12-01 09:24:00United Kingdomsale
2489517163292009-12-01 11:34:00United Kingdomsale
3C489528167142009-12-01 11:50:00United Kingdomcancellation
4489529179842009-12-01 11:51:00United Kingdomsale
5489532133942009-12-01 11:58:00United Kingdomsale
6489540129132009-12-01 12:18:00United Kingdomsale
order_idnumber · unique id
1
invoice_notext
489438
customer_idnumber · links to customers
18102
ordered_atdate & time
2009-12-01 09:24:00
countrytext
United Kingdom
order_typetext
sale
order_idnumber · unique id
2
invoice_notext
489517
customer_idnumber · links to customers
16329
ordered_atdate & time
2009-12-01 11:34:00
countrytext
United Kingdom
order_typetext
sale
order_idnumber · unique id
3
invoice_notext
C489528
customer_idnumber · links to customers
16714
ordered_atdate & time
2009-12-01 11:50:00
countrytext
United Kingdom
order_typetext
cancellation
order_idnumber · unique id
4
invoice_notext
489529
customer_idnumber · links to customers
17984
ordered_atdate & time
2009-12-01 11:51:00
countrytext
United Kingdom
order_typetext
sale
order_idnumber · unique id
5
invoice_notext
489532
customer_idnumber · links to customers
13394
ordered_atdate & time
2009-12-01 11:58:00
countrytext
United Kingdom
order_typetext
sale
order_idnumber · unique id
6
invoice_notext
489540
customer_idnumber · links to customers
12913
ordered_atdate & time
2009-12-01 12:18:00
countrytext
United Kingdom
order_typetext
sale

first 6 of 6,722 rows · your queries use all of them

solution.sql
 

Hints and the answer are always available. Using them counts the question as solved with help.

Build a country history from invoices — SQL practice · Runtime