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