0

如果标题看起来很荒谬并且缺少信息,我深表歉意,我试图通过以下示例来解释这种情况:

考虑下表-

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 不是唯一的。问题是识别在(基于时间)EventB之后有EventC的ID

4

1 回答 1

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 
于 2013-03-21T10:40:04.867 回答