postgresql选择不同的最新记录
我有一张像这样的桌子:postgresql选择不同的最新记录,sql,postgresql,greatest-n-per-group,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 可以使用相关子查询 select * from tablename where srno in (select max(srno) from tablename b where a.
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
可以使用相关子查询
select * from tablename where srno in
(select max(srno) from tablename b where a.fkey=b.fkey)
使用窗口功能
行号()
你可以用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
在Postgres中执行此操作的最佳方法是在上使用
DISTINCT:
SELECT DISTINCT ON (fkey) id, fkey, srno
FROM yourTable
ORDER BY fkey, srno DESC;
您可以在
操作符中使用带有的子查询
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
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