我在 PostgreSQL 9.2 中有一个表,它看起来像这样(简化):
CREATE TABLE my_features
(
id integer NOT NULL,
feature_id integer NOT NULL,
begin_time timestamp NOT NULL,
end_time timestamp
)
对于每个 feature_id,可能会有多行数据,时间范围由 begin_time/end_time 指定。它们可能会重叠,但这种情况相对较少。我正在寻找一种快速的方法来查找所有具有/不具有 任何 重叠的 feature_id。
我尝试使用窗口函数来实现此目的,如下所示:
SELECT feature_id, bool_or(end_time > lead(begin_time) OVER ts_win) OVER ts_win AS overlaps_any
FROM my_features
WINDOW ts_win AS (PARTITION BY feature_id ORDER BY begin_time)
...但这并不起作用:
ERROR: window function calls cannot be nested
算法很简单:按照begin_time对给定feature_id的行进行排序,然后检查是否有任何end_time > 下一个begin_time(如果有)。我怀疑可能有一种简单的方法可以做到这一点,也许是使用tsrange函数,但现在似乎找不到。