For each signup-year cohort, return the cohort year, the number of customers, and how many of them made at least one…
SQLLevel: IntermediateCore interview patterns
For each signup-year cohort, return the cohort year, the number of customers, and how many of them made at least one transaction in 2026 (active_2026), in year order. Cohort analysis shows up constantly in analytics interviews.
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: LEFT JOIN down to transactions with YEAR(t.date) = 2026 inside the ON clause; COUNT(DISTINCT CASE WHEN t.id IS NOT NULL THEN c.id END).
SELECT YEAR(c.signup_date) AS cohort_year,
COUNT(DISTINCT c.customer_id) AS customers,
COUNT(DISTINCT CASE WHEN t.transaction_id IS NOT NULL
THEN c.customer_id END) AS active_2026
FROM customers c
LEFT JOIN accounts a ON a.customer_id = c.customer_id
LEFT JOIN transactions t ON t.account_id = a.account_id
AND YEAR(t.transaction_date) = 2026
GROUP BY cohort_year
ORDER BY cohort_year;
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