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

Sql 基于组ID子集的时间戳列的组中的最后一行-Postgres,sql,postgresql,date,group-by,greatest-n-per-group,Sql,Postgresql,Date,Group By,Greatest N Per Group,给出以下格式的postgres表格: 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+0

给出以下格式的postgres表格:

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

您应该能够通过
分区
行编号()来执行此操作。

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