Return customerid and the number of days between their first and last order (spandays). Table definitions (from the…
SQLLevel: IntermediateDates and time
Return customer_id and the number of days between their first and last order (span_days).
Table definitions (from the source exercise):
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: DATEDIFF(MAX, MIN) grouped by customer.
SELECT customer_id,
DATEDIFF(MAX(order_date), MIN(order_date)) AS span_days
FROM orders
GROUP BY customer_id;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT