一、基础数据
基本数据: 公司id, 数量, 创建时间
3条数据中, 2个公司, 不同的数量和时间
分组找到公司最新的数量
mysql8 有别于5.6, 5.7, 5.x版本自行百度.
MySQL 8 引入了一个 rank()
函数,可以更简便的实现排行的功能.
二、实例展示
具体使用:
select t.company_id, t.quantity,
RANK() OVER(PARTITION BY
t.company_id ORDER BY create_time desc
) ranks
from hd_service_order_item t
得到, 已经能看到排行了
三、结果展示
加上子查询,找到第一: 最后的条件可以随便改, <=3, 可以取前三
select * from (
select t.company_id, t.quantity,
RANK() OVER(PARTITION BY
t.company_id ORDER BY create_time desc
) ranks
from hd_service_order_item t
)f where f.ranks = 1
结果展示: