PostgreSQL选择不同的最新记录

时间:2018-11-21 05:43:52

标签: 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

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

2  A001  2
4  A003  1
5  A002  2

4 个答案:

答案 0 :(得分:1)

使用窗口功能row_number()

select * from (
select *,row_number() over(PARTITION by fkey order by srno desc) rn from table1 t1 
) t where rn=1

您可以使用cte编写

with cte as
(
    select *,row_number() over(PARTITION by fkey order by srno desc) rn from 
    table_name t1
) select * from cte where rn=1

答案 1 :(得分:1)

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

SELECT DISTINCT ON (fkey) id, fkey, srno
FROM yourTable
ORDER BY fkey, srno DESC;

enter image description here

Demo

答案 2 :(得分:0)

您可以使用相关子查询

select * from tablename where srno in
(select max(srno) from tablename b where a.fkey=b.fkey)

答案 3 :(得分:0)

您可以将子查询与IN运算符一起使用

with tab(id, fkey, srno) as 
(
 select 1,'A001',1 union all
 select 2,'A001',2 union all    
 select 3,'A002',1 union all
 select 4,'A003',1 union all    
 select 5,'A002',2   
)
select *
  from tab
 where ( fkey, srno ) in
 (
  select fkey, max(srno)
    from tab
   group by fkey
 );

id  fkey    srno
2   A001     2
4   A003     1
5   A002     2

Rextester Demo