3

我有一个包含数字范围列表的表格。我需要知道这些数字范围中的任何一个是否相互重叠

SQL小提琴在这里

例如,小提琴中的最后 2 行相互重叠。我不确定您甚至会如何在查询结果中显示这一点。

任何帮助,将不胜感激。

编辑:不确定这是否可行,但似乎是:

SELECT
  *
FROM
(
  SELECT
    FROM_NUM,
    TO_NUM,
    LEAD(FROM_NUM) OVER (ORDER BY FROM_NUM) A
  FROM
    RANGES
) RANGES
WHERE
  A < TO_NUM
4

1 回答 1

1
SELECT RANGES.FROM_NUM AS BASE_FROM_NUM,  RANGES.TO_NUM AS BASE_TO_NUM,
  OVERLAP.FROM_NUM AS OVERLAP_FROM_NUM, OVERLAP.TO_NUM AS OVERLAP_TO_NUM
FROM RANGES
INNER JOIN RANGES OVERLAP 
ON (((OVERLAP.FROM_NUM <= RANGES.FROM_NUM) AND (OVERLAP.TO_NUM >= RANGES.FROM_NUM))
OR ((OVERLAP.FROM_NUM <= RANGES.TO_NUM) AND (OVERLAP.TO_NUM >= RANGES.TO_NUM)))
AND ((OVERLAP.FROM_NUM <> RANGES.FROM_NUM) AND (OVERLAP.TO_NUM <> RANGES.TO_NUM))

最后一行只是停止为自己报告重叠的行。在实践中,您可以使用唯一键删除它们(以防万一您有具有相同 from/to 数字的重复行):

AND (OVERLAP.ID <> RANGES.ID)
于 2013-10-11T02:08:37.997 回答