Return the customerid of customers who had transactions in at least 3 consecutive calendar months. This is the classic…
SQLLevel: IntermediateCore interview patterns
Return the customer_id of customers who had transactions in at least 3 consecutive calendar months. This is the classic "gaps and islands" pattern - the hardest thing likely to appear; even a clearly narrated partial attempt scores well.
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 accounts(account_id INTEGER PRIMARY KEY, customer_id INTEGER, product_type TEXT, open_date TEXT, credit_limit INTEGER, status TEXT);
CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, account_id INTEGER, transaction_date TEXT, amount REAL, merchant_category TEXT);
Hints
- Write an interleaving of two concurrent operations.
- Which observations does the isolation level permit, and what happens on a mid-operation failure?
Answer
Approach: Turn each active month into a number (YEAR12 + MONTH), dedupe per customer, then month_number minus ROW_NUMBER() is constant within a consecutive run. GROUP BY that constant, HAVING COUNT() >= 3.
WITH months AS (
SELECT DISTINCT a.customer_id,
YEAR(t.transaction_date) * 12 + MONTH(t.transaction_date) AS mn
FROM accounts a
JOIN transactions t ON t.account_id = a.account_id
),
runs AS (
SELECT customer_id, mn,
mn - ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY mn) AS grp
FROM months
)
SELECT DISTINCT customer_id
FROM runs
GROUP BY customer_id, grp
HAVING COUNT(*) >= 3;
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