Monthly Transactions I
MediumLeetCodeSQL: CASE, String & Date Functions
Hint and exampleShowHide
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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Triangle Judgement | LeetCode | Easy | Solve Triangle Judgement on LeetCode (opens in a new tab) | |||
| 2 | Fix Names in a Table | LeetCode | Easy | Solve Fix Names in a Table on LeetCode (opens in a new tab) | |||
| 3 | Rising Temperature | LeetCode | Easy | Solve Rising Temperature on LeetCode (opens in a new tab) | |||
| 4 | Group Sold Products By The Date | LeetCode | Easy | Solve Group Sold Products By The Date on LeetCode (opens in a new tab) | |||
| 5 | Monthly Transactions I | LeetCode | Medium | Solve Monthly Transactions I on LeetCode (opens in a new tab) | |||
| 6 | Confirmation Rate | LeetCode | Medium | Solve Confirmation Rate on LeetCode (opens in a new tab) |