我在 MySql 5.X 中有一个表,其中标识符根据日期重复重复。我需要恢复每个标识符的前 2 条记录。
例子:
name year month
xxxx 2019 8
xxxx 2019 7
xxxx 2019 6
xxxx 2019 5
.... .... ..
zzzz 2019 5
zzzz 2019 4
zzzz 2019 3
zzzz 2019 2
.... .... ..
预期结果:
name year month
xxxx 2019 8
xxxx 2019 7
zzzz 2019 5
zzzz 2019 4
other ...
我需要为每个名字检索前两条记录,使用日期子句这样做是无效的。
谢谢。
最佳答案
在 MySQL 8.x 中,您可以使用 ROW_NUMBER()
窗口函数为行分配数字。然后过滤你需要的是很容易的。例如:
select *
from (
select
name, year, month,
row_number() over(partition by name order by year desc, month desc) as rn
from t
) x
where rn <= 2
order by name, year desc, month desc
关于mysql - mysql 检索一定数量的同字段记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642435/