Return each account's single largest transaction: accountid, transactiondate, amount. If two tie, either is accepted -…
SQLLevel: IntermediateWindow functions
Return each account's single largest transaction: account_id, transaction_date, amount. If two tie, either is accepted - use ROW_NUMBER.
Table definitions (from the source exercise):
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: ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY amount DESC) in a subquery, then filter rn = 1 outside.
SELECT account_id, transaction_date, amount
FROM (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY amount DESC, transaction_id) AS rn
FROM transactions t
) x
WHERE rn = 1;
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