Select 组中具有特定列 postgres 中最大值的行

Select row in group with largest value in particular column postgres

我有一个数据库 table,看起来像这样。

 id       account_id      action             time_point

 3        234            delete                100
 1        656            create                600
 1        4435           update                900
 3        645            create                50

我需要按 id 和 select 特定行对 table 进行分组,其中 time_point 具有最大值。

结果 table 应如下所示:

 id       account_id      action             time_point

 3        234            delete                100
 1        4435           update                900

感谢您的帮助, 哇

检查这个。

select * from x
where exists (
  select 1 from x xin
  where xin.id = x.id 
  having max(time_point) = time_point
);

在 Postgres 中,我建议 distinct on 解决这个每组前 1 的问题:

select distinct on (id) *
from mytable
order by id, time_point desc

但是,这不允许有可能的关系。如果是这样,rank() 是更好的解决方案:

select *
from (
    select t.*, rank() over(partition by id order by time_point desc) rn
    from mytable t
) t
where rn = 1

或者,如果您是 运行 Postgres 13:

select *
from mytable t
order by rank() over(partition by id order by time_point desc)
fetch first row with ties