如果标题看起来很荒谬并且缺乏信息,我很抱歉,我试图通过以下示例来解释这种情况:
考虑下表 -
ID Event Time
---------------------
1 EventA ta
1 EventB tx
2 EventB ty
1 EventC tb
2 EventC to
我希望选择ID,以便在(基于时间)任何EventB实例之后有一个EventC。
我能想到以下问题:
select ID from TabET where
((select TIME from TabET where Event = EventC order by TIME desc fetch first row only)
>
(select TIME from TabET where Event = EventB order by TIME desc fetch first row only))
我正在寻找一种更好的方法和替代方法,因为现实中的表是一个非常大的表,并且这个查询只是满足条件的大查询中的子查询。
ID不是唯一的。问题是在(基于TIME)事件B
之后识别出具有EventC的ID答案 0 :(得分:1)
您可以使用自我加入:
select distinct t1.ID
from table t1
join table t2 on
t1.ID = t2.ID and
t1.Event = 'EventB' and
t2.Event = 'EventC' and
t2.Time > t1.Time
另一种方法:
with latest_times as (
select id, max(time) as time from table
where Event='EventC'
group by id
)
select t1.ID from table t1
join latest_times on
t1.id = latest_times.id and
t1.Event = 'EventB' and
latest_times.time > t1.time