9. Orders before sign-up Solved
CoreHarddata qualityjoin conditiondate_diff
A bad import left some orders dated before their customer signed up. Ignoring those, return for each customer with at least one valid order: customer_id, name, signed_up, first_order (date of their first valid order) and days_to_first_order. Sort by days_to_first_order descending, then customer_id.
Your answer returns 20 rows with the columns customer_id, name, signed_up, first_order, days_to_first_order. Order matters.
The data
The store from the DuckDB playground, running in your browser with DuckDB. Prices are in EUR; the data covers 2024.
customers20 rows
id | INTEGER primary key |
name | VARCHAR |
country | VARCHAR |
currency | VARCHAR EUR, GBP, USD or JPY |
signed_up | DATE |
tags | VARCHAR[] a list: vip, newsletter, b2b, returns-often |
products10 rows
id | INTEGER primary key |
name | VARCHAR |
category | VARCHAR |
price | DECIMAL(10,2) EUR |
specs | STRUCT weight_g INTEGER, color VARCHAR, sizes VARCHAR[] |
orders300 rows
id | INTEGER primary key |
customer_id | INTEGER → customers.id |
placed_at | TIMESTAMP 2024 |
status | ENUM placed, paid, shipped, delivered, returned |
currency | VARCHAR the customer's currency |
order_items576 rows
order_id | INTEGER → orders.id |
product_id | INTEGER → products.id |
quantity | INTEGER |
unit_price | DECIMAL(10,2) EUR |
web_events20,000 rows
event_id | BIGINT |
ts | TIMESTAMP |
session_id | VARCHAR |
customer_id | INTEGER NULL for anonymous visitors |
event_type | VARCHAR page_view, search, add_to_cart, checkout |
page | STRUCT path, referrer |
device | STRUCT browser, mobile BOOLEAN, screen STRUCT(w, h) |
product_ids | INTEGER[] |
load_ms | INTEGER |
fx_rates720 rows
currency | VARCHAR USD, GBP, JPY |
valid_from | TIMESTAMP |
per_eur | DOUBLE units of currency per 1 EUR |
Hints
date_diff('day', start, end).Common traps
- Taking
min(placed_at)over all orders gives negative day counts.
Solution
SELECT c.id AS customer_id, c.name, c.signed_up,
min(o.placed_at)::DATE AS first_order,
date_diff('day', c.signed_up, min(o.placed_at)::DATE) AS days_to_first_order
FROM customers c
JOIN orders o ON o.customer_id = c.id AND o.placed_at >= c.signed_up
GROUP BY c.id, c.name, c.signed_up
ORDER BY days_to_first_order DESC, customer_id
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.