SQL 查找最后 3 个状态相同的记录

SQL to find records with last 3 same status

我有以下任务table:

id  type   submit_time   status

我需要 运行 一个查询 returns 只有他们最后 3 个任务完成且状态为“失败”的类型。

我该怎么做? 我应该使用 window 函数吗?

谢谢

使用row_number()得到最后三行后可以使用聚合和过滤:

select type
from (select t.*,
             row_number() over (partition by type order by submit_time desc) as seqnum
      from t
     ) t
where seqnum <= 3
group by type
having min(status) = max(status) and min(status) = 'FAILED' and
       count(*) = 3;

其实稍微简单一点的方法是:

select type
from (select t.*,
             row_number() over (partition by type order by submit_time desc) as seqnum
      from t
     ) t
where seqnum <= 3 and status = 'FAILED'
group by type
having count(*) = 3;