Skip to content
Quantoros

Return each customer's name, total spend rounded to 2 decimals, and their percent of all customers' spend rounded to 1…

SQLLevel: IntermediateCore interview patterns

Return each customer's name, total spend rounded to 2 decimals, and their percent of all customers' spend rounded to 1 decimal (pct_of_total), highest spender first. Percent-of-total with a window over an aggregate is a favorite senior-level pattern.

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
  • Which rows belong to the partition and frame for each current row?
  • Check ordering, ties, frame boundaries and the difference from GROUP BY.

Answer

Approach: Aggregate per customer in a CTE, then divide by SUM(total) OVER () - an empty OVER () spans everything.

WITH per_cust AS (
  SELECT c.name, SUM(t.amount) AS total
  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
)
SELECT name, ROUND(total, 2) AS total,
       ROUND(100.0 * total / SUM(total) OVER (), 1) AS pct_of_total
FROM per_cust
ORDER BY total DESC;

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