Return the names of customers who hold more than 2 accounts, with their account count. Table definitions (from the…
SQLLevel: IntermediateJoins
Return the names of customers who hold more than 2 accounts, with their account count.
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);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: JOIN customers to accounts, GROUP BY the customer, filter the count in HAVING.
SELECT c.name, COUNT(a.account_id) AS num_accounts
FROM customers c
JOIN accounts a ON a.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(a.account_id) > 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