Skip to content
Quantoros

Return the top 5 customers by total transaction amount across all their accounts: name and total spend, highest first.…

SQLLevel: IntermediateJoins

Return the top 5 customers by total transaction amount across all their accounts: name and total spend, highest first.

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: customers -> accounts -> transactions, GROUP BY customer, ORDER BY the sum DESC, LIMIT 5.

SELECT c.name, SUM(t.amount) AS total_spend
FROM customers c
JOIN accounts a ON a.customer_id = c.customer_id
JOIN transactions t ON t.account_id = a.account_id
GROUP BY c.customer_id, c.name
ORDER BY total_spend DESC
LIMIT 5;

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

Related questions