본문 바로가기
Data Analysis/Query

리트코드 : 3220. Odd and Even Transactions

by 베짱이28호 2024. 9. 16.

리트코드 : 3220. Odd and Even Transactions


문제

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      |
+------------------+---------+----------+

Explanation:

For transaction dates:
2024-07-01:
Sum of amounts for odd transactions: 75
Sum of amounts for even transactions: 150 + 200 = 350
2024-07-02:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 300 + 50 = 350
2024-07-03:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 120
Note: The output table is ordered by transaction_date in ascending order.
  • 각 날짜별 주문 번호 홀짝에 따른 합계

문제 풀이

MySQL

SELECT transaction_date, SUM(IF (AMOUNT%2=1,AMOUNT,0)) AS ODD_SUM, SUM(IF (AMOUNT%2=0,AMOUNT,0)) AS EVEN_SUM
FROM transactions
GROUP BY transaction_date
ORDER BY 1 ASC
  • GROUP BY + SUMIF 사용해주기.

Pandas

import pandas as pd

def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame:
    grouped = transactions.groupby('transaction_date').agg(
        odd_sum = ('amount', lambda df: df[transactions['amount']%2==1].sum()),
        even_sum = ('amount', lambda df: df[transactions['amount']%2==0].sum())
    ).reset_index()
    grouped.sort_values('transaction_date', inplace=True)
    return grouped
  • group by + lambda sum
  • groupby 이후 lambda로 받는 객체가 DataFrame이라 x로 표현하는거 보다 df로 표현하는게 더 좋은 것 같다.
  • apply 시 lambda로 받을 때는 row가 들어오므로 x대신 row로 표현하는 습관 들이기.

코멘트

  • 무료 리트코드 문제 끝!

댓글