Skip to content
Quantoros

For each customer with transactions, return their top 3 merchant categories by total spend: customerid,…

SQLLevel: IntermediateCore interview patterns

For each customer with transactions, return their top 3 merchant categories by total spend: customer_id, merchant_category, total spend. Break spend ties alphabetically by category.

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: Aggregate per customer per category first (CTE), then ROW_NUMBER() OVER (PARTITION BY customer ORDER BY spend DESC, category), filter rn <= 3 outside.

WITH cat AS (
  SELECT a.customer_id, t.merchant_category, SUM(t.amount) AS spend
  FROM accounts a
  JOIN transactions t ON t.account_id = a.account_id
  GROUP BY a.customer_id, t.merchant_category
)
SELECT customer_id, merchant_category, spend
FROM (
  SELECT cat.*, ROW_NUMBER() OVER (PARTITION BY customer_id
                                   ORDER BY spend DESC, merchant_category) AS rn
  FROM cat
) x
WHERE rn <= 3;

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