postgresql 选择不同的最新记录

Kul*_*kur 9 sql postgresql greatest-n-per-group

我有一个像这样的表:

id  fkey  srno  remark  date
1   A001  1
2   A001  2
3   A002  1
4   A003  1 
5   A002  2
Run Code Online (Sandbox Code Playgroud)

我想要基于 max srno 的不同最新记录,例如

2  A001  2
4  A003  1
5  A002  2
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 11

在 Postgres 中执行此操作的最佳方法是使用DISTINCT ON

SELECT DISTINCT ON (fkey) id, fkey, srno
FROM yourTable
ORDER BY fkey, srno DESC;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

演示


Fah*_*hmi 0

您可以使用相关子查询

select * from tablename where srno in
(select max(srno) from tablename b where a.fkey=b.fkey)
Run Code Online (Sandbox Code Playgroud)