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

问题描述 投票:0回答:1

给出以下形式的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 

提前感谢您的考虑和回复

sql postgresql date group-by greatest-n-per-group
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.