我有下表:
+--------+-------+------+--+
| Object | Event | Time | |
+--------+-------+------+--+
| Obj1 | A | 1 | |
| Obj1 | B | 3 | |
| Obj2 | A | 7 | |
| Obj2 | B | 4 | |
+--------+-------+------+--+
Run Code Online (Sandbox Code Playgroud)
我的目标是获取所有同时发生事件A和B的对象,条件是A首先发生(及时)。到目前为止,我只想出查询来查找所有具有A和B的对象,而没有包括时间:
SELECT DISTINCT Object
FROM
(SELECT *
FROM
(SELECT *
FROM table
INNER JOIN
(SELECT Object Obj
FROM table
WHERE event LIKE '%A%' AS temp_table) ON table.Object = temp_table.Obj) AS temp_final
WHERE event LIKE '%B%') AS temp2;
Run Code Online (Sandbox Code Playgroud)
因此,最终结果将是我得到一个仅包含以下内容的表:
Obj1
Run Code Online (Sandbox Code Playgroud)
因为这是唯一满足所有条件的对象。
时间列是现实生活中的日期戳,但为简单起见,我使用了整数。
谢谢你的帮助
如果您只跟踪相继发生的两个事件,那么您可以使用单个JOIN.
无论事件的数量Obj1如何,这都将起作用,正如您所提到的,您只对一个接一个的事件感兴趣A,并且存在和存在。B
select distinct t1.object
from TABLE t1
inner join TABLE t2 on t1.object = t2.object
and t2.time > t1.time
and t1.event = 'A'
and t2.event = 'B'
Run Code Online (Sandbox Code Playgroud)
以下是代码结果的示例:
declare @tbl table (obj varchar(10), event varchar(1), time int)
insert @tbl values ('Obj1', 'A', 1), ('Obj1', 'B', 3), ('Obj2', 'A', 7), ('Obj2', 'B', 4)
select distinct t1.obj
from @tbl t1
inner join @tbl t2 on t1.obj = t2.obj
and t2.time > t1.time
and t1.event = 'A'
and t2.event = 'B'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
891 次 |
| 最近记录: |