返回介绍

solution / 1800-1899 / 1831.Maximum Transaction Each Day / README_EN

发布于 2024-06-17 01:03:14 字数 3157 浏览 0 评论 0 收藏 0

1831. Maximum Transaction Each Day

中文文档

Description

Table: Transactions

+----------------+----------+
| Column Name  | Type   |
+----------------+----------+
| transaction_id | int    |
| day      | datetime |
| amount     | int    |
+----------------+----------+
transaction_id is the column with unique values for this table.
Each row contains information about one transaction.

 

Write a solution to report the IDs of the transactions with the maximum amount on their respective day. If in one day there are multiple such transactions, return all of them.

Return the result table ordered by transaction_id in ascending order.

The result format is in the following example.

 

Example 1:

Input: 
Transactions table:
+----------------+--------------------+--------+
| transaction_id | day        | amount |
+----------------+--------------------+--------+
| 8        | 2021-4-3 15:57:28  | 57   |
| 9        | 2021-4-28 08:47:25 | 21   |
| 1        | 2021-4-29 13:28:30 | 58   |
| 5        | 2021-4-28 16:39:59 | 40   |
| 6        | 2021-4-29 23:39:28 | 58   |
+----------------+--------------------+--------+
Output: 
+----------------+
| transaction_id |
+----------------+
| 1        |
| 5        |
| 6        |
| 8        |
+----------------+
Explanation: 
"2021-4-3"  --> We have one transaction with ID 8, so we add 8 to the result table.
"2021-4-28" --> We have two transactions with IDs 5 and 9. The transaction with ID 5 has an amount of 40, while the transaction with ID 9 has an amount of 21. We only include the transaction with ID 5 as it has the maximum amount this day.
"2021-4-29" --> We have two transactions with IDs 1 and 6. Both transactions have the same amount of 58, so we include both in the result table.
We order the result table by transaction_id after collecting these IDs.

 

Follow up: Could you solve it without using the MAX() function?

Solutions

Solution 1: Window Function

We can use the window function RANK(), which assigns a rank to each transaction based on its amount in descending order, and then select the transactions with a rank of $1$.

# Write your MySQL query statement below
WITH
  T AS (
    SELECT
      transaction_id,
      RANK() OVER (
        PARTITION BY DAY(day)
        ORDER BY amount DESC
      ) AS rk
    FROM Transactions
  )
SELECT transaction_id
FROM T
WHERE rk = 1
ORDER BY 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文