基于时间戳列的组中最后一行组 ID 的子集 - Postgres

Last Row In Group Based on Timestamp Column For a Subset of Group Ids - Postgres

给定以下形式的 postgres table:

group id | timestamp                     | value
---------+-------------------------------+------
       1 | 2020-04-15 15:04:44.020288+00 | 8.0
       2 | 2020-04-15 15:05:44.020288+00 | 9.0
       3 | 2020-04-15 15:06:44.020288+00 | 10.0
       4 | 2020-04-15 15:07:44.020288+00 | 11.0
       1 | 2020-04-15 15:08:44.020288+00 | 12.0
       2 | 2020-04-15 15:09:44.020288+00 | 13.0
       3 | 2020-04-15 15:10:44.020288+00 | 14.0
       4 | 2020-04-15 15:11:44.020288+00 | 15.0

根据时间戳列检索组 ID 子集的最后一行的 SQL 查询是什么?

例如,检索组 ID {1,3} 的最后一行以生成:

group id | timestamp                     | value
---------+-------------------------------+------
       1 | 2020-04-15 15:08:44.020288+00 | 12.0
       3 | 2020-04-15 15:10:44.020288+00 | 14.0 

提前感谢您的考虑和回复

在 Postgres 中解决这个每组最大 n 问题的一个简单有效的方法是使用 distinct on:

select distinct on (group_id) t.*
from mytable t
where group_id in (1, 3)
order by group_id, timestamp desc

您应该可以通过 partitionrow_number():

with cte1 as (
  select
    *,
    row_number() over (partition by group_id order by timestamp desc) as row_number
  from yourtable t
)

select *
from cte1
where row_number = 1