MySQL高阶1831-每天的最大交易

题目

编写一个解决方案,报告每天交易金额 amount 最大 的交易 ID 。如果一天中有多个这样的交易,返回这些交易的 ID 。

返回结果根据 transaction_id 升序排列

准备数据

sql 复制代码
Create table If Not Exists Transactions (transaction_id int, day date, amount int);
    Truncate table Transactions;
    insert into Transactions (transaction_id, day, amount) values ('8', '2021-4-3 15:57:28', '57');
    insert into Transactions (transaction_id, day, amount) values ('9', '2021-4-28 08:47:25', '21');
    insert into Transactions (transaction_id, day, amount) values ('1', '2021-4-29 13:28:30', '58');
    insert into Transactions (transaction_id, day, amount) values ('5', '2021-4-28 16:39:59', '40');
    insert into Transactions (transaction_id, day, amount) values ('6', '2021-4-29 23:39:28', '58');

分析数据

第一步:使用开窗函数根据amount降序

sql 复制代码
select *,
       rank() over(partition by day order by amount desc) rn
       from transactions;

第二步:选出最大交易金额的交易ID

sql 复制代码
with t1 as (
    select *,
           rank() over(partition by day order by amount desc) rn
    from transactions
)select transaction_id from t1
where rn =1
order by transaction_id asc;
相关推荐
笃行3507 分钟前
MySQL 的 JSON 字段迁到金仓还能用吗?——KingbaseES V9R3C18 JSON 操作符与函数兼容实测
数据库
IpdataCloud1 小时前
跨境AI金融风险怎么防?IP风险画像的实战应用指南
数据库·tcp/ip·金融·ip
Alan_753 小时前
API 接口慢调用根因定位:从 TCP 建连到数据库 IO 的全栈排查实战
数据库
多巴胺梦想家4 小时前
事务与并发控制:当多人同时操作数据库
服务器·数据库·oracle
howard20055 小时前
PostgreSQL起步
数据库·postgresql
孙晓鹏life5 小时前
MySQL-Seconds_behind_master的精度误差
android·mysql·adb
秋田君5 小时前
QT_QT布局详解
开发语言·数据库·qt
可乐ea6 小时前
【Redis八股|第8篇】Redis 分布式锁原理与 Redisson 使用
数据库·redis·分布式·面试题·redis八股
李燚6 小时前
Eino devops 调试系统源码:GraphCompileCallback 怎么工作(第50篇-E36)
数据库·golang·agent·devops·graphql·aiagent·eino