Return one number, avgcustomerspend: the average of each customer's total spend. (This is different from AVG(amount) -…
SQLLevel: IntermediateSubqueries and CTEs
Return one number, avg_customer_spend: the average of each customer's total spend. (This is different from AVG(amount) - say out loud why.)
Table definitions (from the source exercise):
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: First aggregate to one row per customer (derived table or CTE), then average that column.
WITH per_cust AS (
SELECT a.customer_id, SUM(t.amount) AS total_spend
FROM accounts a
JOIN transactions t ON t.account_id = a.account_id
GROUP BY a.customer_id
)
SELECT AVG(total_spend) AS avg_customer_spend
FROM per_cust;
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