A payments analyst wants to know which payment methods bring in the most money, ignoring anything that did not go through.
From payment_txns, count the successful transactions and add up their amounts for each method. Return method, txn_count and total_amount, with the highest total_amount first.
Sample data
Table: payment_txns
15 row(s) · showing first 8
| txn_idINT | methodTEXT | amountNUMERIC(10,2) | statusTEXT |
|---|---|---|---|
| 1 | UPI | 1200.00 | SUCCESS |
| 2 | UPI | 450.50 | SUCCESS |
| 3 | Card | 8999.00 | SUCCESS |
| 4 | Card | 2300.00 | FAILED |
| 5 | NetBanking | 5600.00 | SUCCESS |
| 6 | UPI | 780.00 | FAILED |
| 7 | Wallet | 299.00 | SUCCESS |
| 8 | Card | 15400.00 | SUCCESS |
payment_txns
- txn_idINT
- methodTEXT
- amountNUMERIC(10,2)
- statusTEXT
- Step 1: Filter first with `WHERE status = 'SUCCESS'`; row-level filters belong in `WHERE`, not `HAVING`.
- Step 2: `GROUP BY method` collapses the remaining rows into one row per payment method.
- Step 3: `COUNT(*)` and `SUM(amount)` are computed per group, then `ORDER BY total_amount DESC` ranks the methods.
SELECT method,
COUNT(*) AS txn_count,
SUM(amount) AS total_amount
FROM payment_txns
WHERE status = 'SUCCESS'
GROUP BY method
ORDER BY total_amount DESC;More GROUP BY questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program