Aggregation and Grouping · Problem 41 of 118

Largest Withdrawal per Account

HardAggregation and GroupingBank data

Considering only transactions with kind = 'withdrawal', return account_id and largest_withdrawal_cents (the biggest single withdrawal of that account) for the five accounts with the largest such withdrawal. Sort by largest_withdrawal_cents from high to low, then by account_id.

Hint 1

WHERE removes the other kinds before GROUP BY and MAX.

Reference solution

SELECT account_id, MAX(amount_cents) AS largest_withdrawal_cents
FROM transactions
WHERE kind = 'withdrawal'
GROUP BY account_id
ORDER BY largest_withdrawal_cents DESC, account_id
LIMIT 5;

Think in the order the database does: first WHERE kind = 'withdrawal' throws away every other transaction, then GROUP BY account_id forms the groups, then MAX finds the biggest amount in each. Filtering after aggregating (for example with HAVING) would answer a different question.