列表

详情


3220. Odd and Even Transactions

表:transactions

+------------------+------+
| Column Name      | Type | 
+------------------+------+
| transaction_id   | int  |
| amount           | int  |
| transaction_date | date |
+------------------+------+
transactions_id 列唯一标识了表中的每一行。
这张表的每一行包含交易 id,金额总和和交易日期。

编写一个解决方案来查找每天 奇数 交易金额和 偶数 交易金额的 总和。如果某天没有奇数或偶数交易,显示为 0

返回结果表以 transaction_date 升序 排序。

结果格式如下所示。

 

示例:

输入:

transactions 表:

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

输出:

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

解释:

注意:输出表以 transaction_date 升序排序。

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
# Write your MySQL query statement below

pythondata 解法, 执行用时: 397 ms, 内存消耗: 69.4 MB, 提交时间: 2024-07-24 09:05:55

import pandas as pd

def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame:
    data = transactions.groupby('transaction_date').agg(
        odd_sum = ('amount', lambda x: x[transactions['amount']%2 != 0].sum()),
        even_sum = ('amount',lambda x: x[transactions['amount']%2 == 0].sum())
    ).reset_index()
    data['odd_sum'] = data['odd_sum'].fillna(0)
    data['even_sum'] = data['even_sum'].fillna(0)
    return data.sort_values('transaction_date')

mysql 解法, 执行用时: 292 ms, 内存消耗: 0 B, 提交时间: 2024-07-22 09:10:16

# Write your MySQL query statement below
# 找出每天奇数和偶数交易的总金额
select transaction_date, 
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
order by transaction_date;

上一题