Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 跨重复ID查找查询中最近的项_Sql_Postgresql - Fatal编程技术网

Sql 跨重复ID查找查询中最近的项

Sql 跨重复ID查找查询中最近的项,sql,postgresql,Sql,Postgresql,我目前正试图编写一个查询,在一系列具有相同id的行中查找最近的项 本质上,查询应该能够看到每个重复id的子组中最新的项 在上述情况下,应返回第1、3和6行。数据来自一个函数,该函数基本上查找对服务项执行的所有操作以及执行的时间,因此我试图查看最近执行的操作 目前,我编写的查询使用最后一个_值和partition by来创建结果集。我想知道是否有一个更有效的方法来实现这一点,或者可能有一个更可行的解决方案 select distinct x, last_value(t) over

我目前正试图编写一个查询,在一系列具有相同id的行中查找最近的项

本质上,查询应该能够看到每个重复id的子组中最新的项

在上述情况下,应返回第1、3和6行。数据来自一个函数,该函数基本上查找对服务项执行的所有操作以及执行的时间,因此我试图查看最近执行的操作

目前,我编写的查询使用最后一个_值和partition by来创建结果集。我想知道是否有一个更有效的方法来实现这一点,或者可能有一个更可行的解决方案

select distinct
    x, 
    last_value(t) over (
        partition by x order by t
        range between unbounded preceding and unbounded following
    ) as time
from 
   test_table 

我目前正在使用postgres。

您可以在上使用
distinct:

select distinct on (child_service_item_id) t.*
from test_table t
order by child_service_item_id, action_date desc;

您可以使用
不存在
,如下所示:

select t.*
from test_table t
Where not exists
(Select 1 from test_table tt
  Where tt.child_service_item_id = t.child_service_item_id
    And tt.action_date > t.action_date)
Select child_service_item_id, max(action_date)
  From test_table
 Group by child_service_item_id
或者非常简单的方法是
group by
,如下所示:

select t.*
from test_table t
Where not exists
(Select 1 from test_table tt
  Where tt.child_service_item_id = t.child_service_item_id
    And tt.action_date > t.action_date)
Select child_service_item_id, max(action_date)
  From test_table
 Group by child_service_item_id