[SQL 문제 풀이] Monthly Transactions I (월간 트랜잭션 I)

Stupefyee's avatar
Jun 23, 2025
[SQL 문제 풀이] Monthly Transactions I (월간 트랜잭션 I)
Monthly Transactions I - LeetCode
Can you solve this real interview question? Monthly Transactions I - 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. The query result format is in the following example.   Example 1: Input: Transactions table: +------+---------+----------+--------+------------+ | id | country | state | amount | trans_date | +------+---------+----------+--------+------------+ | 121 | US | approved | 1000 | 2018-12-18 | | 122 | US | declined | 2000 | 2018-12-19 | | 123 | US | approved | 2000 | 2019-01-01 | | 124 | DE | approved | 2000 | 2019-01-07 | +------+---------+----------+--------+------------+ Output: +----------+---------+-------------+----------------+--------------------+-----------------------+ | month | country | trans_count | approved_count | trans_total_amount | approved_total_amount | +----------+---------+-------------+----------------+--------------------+-----------------------+ | 2018-12 | US | 2 | 1 | 3000 | 1000 | | 2019-01 | US | 1 | 1 | 2000 | 2000 | | 2019-01 | DE | 1 | 1 | 2000 | 2000 | +----------+---------+-------------+----------------+--------------------+-----------------------+
Monthly Transactions I - LeetCode
notion image
월별 및 국가별로 SQL 쿼리를 작성하여 거래 수와 총액, 승인된 거래 수와 총액을 찾습니다. 결과 테이블을 순서에 상관없이 반환하세요.
 

내가 작성한 쿼리

MySQL

SELECT t2.month, country, COUNT(*) AS trans_count, SUM(CASE WHEN state = 'approved' THEN 1 ELSE 0 END) AS approved_count, SUM(amount) AS trans_total_amount, SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) AS approved_total_amount FROM ( -- 년-월을 나타내는 컬럼을 추가한 테이블 서브쿼리 SELECT *, DATE_FORMAT(trans_date, '%Y-%m') AS month FROM Transactions ) t2 GROUP BY country, month

Oracle

SELECT t2.month, t2.country, COUNT(*) AS trans_count, SUM(CASE WHEN t2.state = 'approved' THEN 1 ELSE 0 END) AS approved_count, SUM(t2.amount) AS trans_total_amount, SUM(CASE WHEN t2.state = 'approved' THEN t2.amount ELSE 0 END) AS approved_total_amount FROM ( -- 년-월 컬럼을 추가한 서브쿼리 SELECT t.*, TO_CHAR(trans_date, 'YYYY-MM') AS month FROM Transactions t ) t2 GROUP BY t2.country, t2.month;

차이점

  • 날짜 포맷 함수 차이
Share article

stupefyee