푸는 데 한참 시간이 걸렸다.
그렇지만 막상 'Accepted'가 뜨고 나면 그렇게 어려운 건 아니었다는 감상이 드는 게 함정...;_;
GROUP BY와 날짜 형식을 바꾸는 것까지는 무난하게 해냈는데, 각 조건에 맞게 집계하고 컬럼명을 올바르게 넣는 것이 의외로 헷갈렸다.
이럴 때는 한 번에 완벽하게 해낼 생각하지 말고 하나씩 트라이 해보고 맞는지 확인한 다음 다음으로 넘어가는 게 정도인 것 같다.
Table: Transactions
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| country | varchar |
| state | enum |
| amount | int |
| trans_date | date |
+---------------+---------+
id is the primary key of this table.
The table has information about incoming transactions.
The state column is an enum of type ["approved", "declined"].
Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount.
Return the result table in any order.
SELECT
DATE_FORMAT(trans_date, '%Y-%m') AS month,
country,
COUNT(*) AS trans_count,
SUM(amount) AS approved_count,
SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS trans_total_amount,
COALESCE(SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END), 0) AS approved_total_amount
FROM Transactions
GROUP BY month, country;