For customers with 2+ orders: return customerid and the average days between consecutive orders rounded to 1 decimal…
SQLLevel: IntermediateDates and time
For customers with 2+ orders: return customer_id and the average days between consecutive orders rounded to 1 decimal (avg_gap).
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
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: LAG date per customer in a CTE, DATEDIFF, then AVG (NULL first-gap is skipped automatically).
WITH g AS (
SELECT customer_id,
DATEDIFF(order_date,
LAG(order_date) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id)) AS gap
FROM orders
)
SELECT customer_id, ROUND(AVG(gap), 1) AS avg_gap
FROM g
GROUP BY customer_id
HAVING COUNT(*) >= 2;
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