In one query on the accounts table, return: total number of accounts, number of distinct customers with an account,…
SQLLevel: FoundationAggregates
In one query on the accounts table, return: total number of accounts, number of distinct customers with an account, and the average credit limit of credit_card accounts only (alias it avg_card_limit).
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: COUNT(*), COUNT(DISTINCT ...), and AVG over a CASE WHEN (or a conditional trick).
SELECT COUNT(*) AS total_accounts,
COUNT(DISTINCT customer_id) AS customers_with_accounts,
AVG(CASE WHEN product_type = 'credit_card' THEN credit_limit END) AS avg_card_limit
FROM accounts;
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