Identify all customers who made over $10,000 in cash payments during any two consecutive calendar days. Table…
SQLLevel: IntermediateSQL scenarios
Identify all customers who made over $10,000 in cash payments during any two consecutive calendar days.
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 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: Step 1: collapse to daily cash totals per customer (CTE). Step 2: self-join each anchor day to itself and the next day; sum and filter with HAVING > 10000.
WITH daily AS (
SELECT customer_id, payment_date, SUM(amount) AS day_cash
FROM payments
WHERE method = 'cash'
GROUP BY customer_id, payment_date
)
SELECT DISTINCT d1.customer_id
FROM daily d1
JOIN daily d2
ON d2.customer_id = d1.customer_id
AND d2.payment_date IN (d1.payment_date, DATE_ADD(d1.payment_date, INTERVAL 1 DAY))
GROUP BY d1.customer_id, d1.payment_date
HAVING SUM(d2.day_cash) > 10000;
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