Skip to content
We areTOP 1%

Monthly Transactions I

MediumLeetCodeSQL: CASE, String & Date Functions
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

Group by a formatted month and a second column, and put CASE expressions inside SUM to compute filtered totals next to the overall totals.

Example: payments(paid_on, city, status, amount)

paid_on    | city | status | amount
2024-01-05 | Pune | ok     | 100
2024-01-20 | Pune | failed | 40
2024-02-02 | Pune | ok     | 70
SELECT DATE_FORMAT(paid_on, '%Y-%m') AS month, city,
       COUNT(*) AS payments,
       SUM(CASE WHEN status = 'ok' THEN 1 ELSE 0 END) AS ok_count,
       SUM(CASE WHEN status = 'ok' THEN amount ELSE 0 END) AS ok_amount
FROM payments
GROUP BY month, city;
-- 2024-01 | Pune | 2 | 1 | 100
-- 2024-02 | Pune | 1 | 1 | 70

More in SQL: CASE, String & Date Functions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account