2016-04-25 32 views
1

選擇行我有一個表SQL:很少有時間差

event_id eventtypeid eventtimestamp

描述,可以是相互接近時的事件。我想查找事件對,其中事件類型相同,時間戳之間的差異不超過3毫秒。

在sql中一般可能嗎?我如何制定這樣的要求?

預先感謝您。

+0

請用你正在使用的數據庫標記你的問題。 –

+0

如果有兩排「火柴」,兩邊各有一排,你想做什麼?這是兩組配對還是一組三聯體? –

+0

@Tom H,tiplets是不可能的:)或者如果他們發生,我可以對所有這些事件相互破碎的事件感到高興 – user2957954

回答

3
SELECT 
    * 
FROM 
    event_table AS first 
INNER JOIN 
    event_table AS second 
    ON second.eventtypeid  = first.eventtypeid 
    AND second.eventtimestamp > first.eventtimestamp 
    AND second.eventtimestamp <= first.eventtimestamp + INTERVAL '3 milliseconds' 
3

查詢像這些一般最好用window function解決:

SELECT eventtypeid, first, second, diff 
FROM (
    SELECT eventtypeid, event_id AS first, lead(event_id) OVER w AS second, 
     lead(eventtimestamp) OVER w - eventtimestamp AS diff 
    FROM event_table 
    WINDOW w AS (PARTITION BY eventtypeid ORDER BY eventtimestamp) 
) sub 
WHERE diff <= interval '3 milliseconds'; 

這通常比自聯接快得多。