For each customer with at least 2 payments, return customerid and their average number of days between consecutive…
SQLLevel: IntermediateServicing and risk analytics
For each customer with at least 2 payments, return customer_id and their average number of days between consecutive payments, rounded to 1 decimal (avg_gap_days). Payment cadence changes are an early delinquency signal.
Table definitions (from the source exercise):
CREATE TABLE payments(payment_id INTEGER PRIMARY KEY, customer_id INTEGER, payment_date TEXT, amount REAL, method TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: LAG(payment_date) per customer ordered by date in a CTE, DATEDIFF current vs previous, then AVG per customer (the first payment has a NULL gap and AVG skips it). HAVING COUNT filters the 1-payment customers.
WITH gaps AS (
SELECT customer_id,
DATEDIFF(payment_date,
LAG(payment_date) OVER (PARTITION BY customer_id
ORDER BY payment_date, payment_id)) AS gap
FROM payments
)
SELECT customer_id, ROUND(AVG(gap), 1) AS avg_gap_days
FROM gaps
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