For each payment method, return the method, the customerid who made the single largest payment, and that amount. Table…
SQLLevel: IntermediateBonus drills (mixed difficulty)
For each payment method, return the method, the customer_id who made the single largest payment, and that amount.
Table definitions (from the source exercise):
CREATE TABLE payments(payment_id INTEGER PRIMARY KEY, customer_id INTEGER, payment_date TEXT, amount REAL, method TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: ROW_NUMBER() OVER (PARTITION BY method ORDER BY amount DESC) in a subquery; keep rn = 1.
SELECT method, customer_id, amount
FROM (
SELECT p.*, ROW_NUMBER() OVER (PARTITION BY method
ORDER BY amount DESC, payment_id) AS rn
FROM payments p
) 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