[SQL]

LeetCode 코딩 테스트 - Odd and Even Transactions(LV.Medium)

indongspace 2025. 4. 4. 00:29

 

 

Table: transactions

+------------------+------+
| Column Name      | Type | 
+------------------+------+
| transaction_id   | int  |
| amount           | int  |
| transaction_date | date |
+------------------+------+
The transactions_id column uniquely identifies each row in this table.
Each row of this table contains the transaction id, amount and transaction date.

Write a solution to find the sum of amounts for odd and even transactions for each day. If there are no odd or even transactions for a specific date, display as 0.

Return the result table ordered by transaction_date in ascending order.

The result format is in the following example.

 

Example:

Input:

transactions table:

+----------------+--------+------------------+
| transaction_id | amount | transaction_date |
+----------------+--------+------------------+
| 1              | 150    | 2024-07-01       |
| 2              | 200    | 2024-07-01       |
| 3              | 75     | 2024-07-01       |
| 4              | 300    | 2024-07-02       |
| 5              | 50     | 2024-07-02       |
| 6              | 120    | 2024-07-03       |
+----------------+--------+------------------+
  

Output:

+------------------+---------+----------+
| transaction_date | odd_sum | even_sum |
+------------------+---------+----------+
| 2024-07-01       | 75      | 350      |
| 2024-07-02       | 0       | 350      |
| 2024-07-03       | 0       | 120      |
+------------------+---------+----------+

 

# 쿼리를 작성하는 목표, 확인할 지표 : 홀수/짝수 별로 amount의 합산 구하기 / amount, transaction_date
# 쿼리 계산 방법 : 1. group by sum(case when)으로 홀수 짝수 별 amount의 sum 구하기 -> 2. 정렬
# 데이터의 기간 : x
# 사용할 테이블 : transactions
# JOIN KEY : x
# 데이터 특징 : x
SELECT
    transaction_date,
    # 1
    SUM(CASE WHEN amount % 2 != 0 THEN amount ELSE 0 END) AS odd_sum,
    SUM(CASE WHEN amount % 2 = 0 THEN amount ELSE 0 END) AS even_sum
FROM transactions
GROUP BY
    transaction_date
# 2
ORDER BY
    transaction_date