我有一张 table
event_id eventtypeid eventtimestamp
描述的是可以相互接近的时间事件。我想找到事件对,其中事件类型相等并且时间戳之间的差异不超过 3 毫秒。
在sql中一般可以吗?我该如何提出这样的要求?
提前谢谢你。
最佳答案
像这样的查询通常最好用 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';
这通常比自连接快得多。
关于Sql:选择时间差很小的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36844662/