在 SQL 查询中查找组中的旧记录
Find older records in a group in a SQL query
我正在尝试在 SQL table 组中查找较旧的记录,以便删除它们。但是我连选择它们都遇到了麻烦。
Table 看起来像这样:
我想做的是只保留每个问题的前 3 个最新更改,我想删除旧的记录。
要找到每期不在前 3 名的内容,需要 SQL 多少?谢谢!
What is the SQL required to find the ones not in the top 3 most recent for each issue?
如果你是运行 MySQL 8.0,使用row_number()
:
select *
from (
select
t.*,
row_number() over(partition by issue_id order by change_date desc) rn
from mytable t
) t
where rn > 3
在早期版本中,您可以使用相关子查询来模拟此操作:
select *
from mytable t
where (
select count(*)
from mytable t1
where t1.issue_id = t.issue_id and t1.change_date > t.change_date
) >= 3
我正在尝试在 SQL table 组中查找较旧的记录,以便删除它们。但是我连选择它们都遇到了麻烦。
Table 看起来像这样:
我想做的是只保留每个问题的前 3 个最新更改,我想删除旧的记录。
要找到每期不在前 3 名的内容,需要 SQL 多少?谢谢!
What is the SQL required to find the ones not in the top 3 most recent for each issue?
如果你是运行 MySQL 8.0,使用row_number()
:
select *
from (
select
t.*,
row_number() over(partition by issue_id order by change_date desc) rn
from mytable t
) t
where rn > 3
在早期版本中,您可以使用相关子查询来模拟此操作:
select *
from mytable t
where (
select count(*)
from mytable t1
where t1.issue_id = t.issue_id and t1.change_date > t.change_date
) >= 3