SQL获取每个组的第二(第n)条记录(postgresql或mysql)

时间:2015-09-04 16:14:06

标签: mysql sql postgresql

我用google搜索和stackoverflowed高低,无法找到任何具体的解决方案来显示每组的第二(第n)记录。

考虑下表(按created_at desc排序):

----------------------------------------------
bid_id | status    | created_at
----------------------------------------------
1      | cancelled | 2015-10-03 
1      | awarded   | 2015-10-02
1      | pending   | 2015-10-01
2      | pending   | 2015-10-01
3      | denied    | 2015-10-02
3      | pending   | 2015-10-01

结果输出应如下所示(按bid_id分组):

bid_id | status    | created_at
----------------------------------------------
1      | awarded   | 2014-10-02
3      | pending   | 2014-10-01

实现这一目标的有效SQL是什么?非常感谢任何提示!

1 个答案:

答案 0 :(得分:7)

您可以使用row_numberbi_id列排序的每个created_at分区中分配行号。然后,您只需选择第二行或您需要的行。这适用于postgres,因为它支持window个函数。

select bid_id, status, created_at
from
(
select bid_id, status, created_at,
row_number() over(partition by bid_id order by created_at desc) as rn
from tablename
) x
where x.rn = 2;