comments | difficulty | edit_url | tags | |
---|---|---|---|---|
true |
中等 |
|
表: Transactions
+------------------+----------+ | Column Name | Type | +------------------+----------+ | user_id | int | | spend | decimal | | transaction_date | datetime | +------------------+----------+ (user_id, transaction_date) 是这张表具有唯一值的列。 该表包含 user_id, spend,和 transaction_date。
编写一个查询,找到符合要求的用户的 第三笔交易 (如果他们有至少三笔交易),并且满足 前两笔交易 的花费 低于 第三笔交易的花费。
返回 按 升序 user_id
排序的结果表。
结果格式如下例所示。
示例 1:
输入: Transactions table: +---------+--------+---------------------+ | user_id | spend | transaction_date | +---------+--------+---------------------+ | 1 | 65.56 | 2023-11-18 13:49:42 | | 1 | 96.0 | 2023-11-30 02:47:26 | | 1 | 7.44 | 2023-11-02 12:15:23 | | 1 | 49.78 | 2023-11-12 00:13:46 | | 2 | 40.89 | 2023-11-21 04:39:15 | | 2 | 100.44 | 2023-11-20 07:39:34 | | 3 | 37.33 | 2023-11-03 06:22:02 | | 3 | 13.89 | 2023-11-11 16:00:14 | | 3 | 7.0 | 2023-11-29 22:32:36 | +---------+--------+---------------------+ 输出 +---------+-------------------------+------------------------+ | user_id | third_transaction_spend | third_transaction_date | +---------+-------------------------+------------------------+ | 1 | 65.56 | 2023-11-18 13:49:42 | +---------+-------------------------+------------------------+ 解释 - 对于 user_id 1,他们的第三笔交易发生在 2023-11-18 13:49:42,金额为 $65.56,超过了前两笔交易的支出,分别是 2023-11-02 12:15:23 的 $7.44 和 2023-11-12 00:13:46 的 $49.78。因此,此第三笔交易将包含在输出表中。 - user_id 2 只有总共 2 笔交易,因此没有第三笔交易。 - 对于 user_id 3,第三笔交易的金额 $7.0 少于前两笔交易,因此不会包含在内。 输出表按升序按 user_id 排序。
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY user_id
ORDER BY transaction_date
) AS rk,
spend > (
LAG(spend) OVER (
PARTITION BY user_id
ORDER BY transaction_date
)
)
AND spend > (
LAG(spend, 2) OVER (
PARTITION BY user_id
ORDER BY transaction_date
)
) AS st
FROM Transactions
)
SELECT user_id, spend AS third_transaction_spend, transaction_date AS third_transaction_date
FROM T
WHERE rk = 3 AND st = 1;