如何在 MS Access 中编写查询来整理与其他记录的时间段重叠的记录?
How to write a query in MS Access to sort out the records that overlap other record's time period?
我有一个中间 table 如下所示
Ref# |Time |id
--------------------------------------
10 |10/23/2020 6:48:03 PM |9
10 |10/23/2020 6:53:56 PM |12 <-- target output record
10 |10/23/2020 7:53:56 PM |9
12 |10/23/2020 7:48:03 PM |11
12 |10/23/2020 7:55:56 PM |11
我的目标是在给定相同 Ref# 的情况下,整理出属于其他 ID 时间线的任何不同 ID。在上面的例子中,id 12 与 id 9 的时间段重叠。非常感谢。
嗯。 . .您似乎想要介于另一个 ID 之间的任何东西。所以,我在想:
select t.*
from t
where exists (select 1
from t as t2
where t2.ref = t1.ref and
t2.id <> t.id
group by t2.id
having t.time > min(t2.time) and
t.time < max(t2.time)
);
或者使用 group by
可能更有效:
select t.*
from t inner join
(select ref, id, min(time) as min_time, amx(time) as max_time
from t
group by ref, id
) as tt
on t.ref = tt.ref and
t.id <> tt.id and
t.time > tt.min_time and
t.time < tt.max_time;
我有一个中间 table 如下所示
Ref# |Time |id
--------------------------------------
10 |10/23/2020 6:48:03 PM |9
10 |10/23/2020 6:53:56 PM |12 <-- target output record
10 |10/23/2020 7:53:56 PM |9
12 |10/23/2020 7:48:03 PM |11
12 |10/23/2020 7:55:56 PM |11
我的目标是在给定相同 Ref# 的情况下,整理出属于其他 ID 时间线的任何不同 ID。在上面的例子中,id 12 与 id 9 的时间段重叠。非常感谢。
嗯。 . .您似乎想要介于另一个 ID 之间的任何东西。所以,我在想:
select t.*
from t
where exists (select 1
from t as t2
where t2.ref = t1.ref and
t2.id <> t.id
group by t2.id
having t.time > min(t2.time) and
t.time < max(t2.time)
);
或者使用 group by
可能更有效:
select t.*
from t inner join
(select ref, id, min(time) as min_time, amx(time) as max_time
from t
group by ref, id
) as tt
on t.ref = tt.ref and
t.id <> tt.id and
t.time > tt.min_time and
t.time < tt.max_time;