一个数字范围减去另一个数字范围

时间:2019-01-21 23:58:36

标签: sql sql-server

我有一个从X到Y的数字间隔(例如x = 100,y = 200,所以间隔是100、101,... 200),并且有两列“ from”和“ two”的表,这意味着另一个间隔,例如

from    to
110    120
130    140

我需要从范围(x,y)中减去表中的所有范围(从,到)。 因此,结果将

100 109 
121 129 
141 200

有可能吗?

1 个答案:

答案 0 :(得分:5)

一种方法是(DEMO

DECLARE @X INT = 100,
        @Y INT = 200;

WITH N(N)
     AS (SELECT @X
         UNION ALL
         SELECT N + 1
         FROM   N
         WHERE  N < @Y),
     T1
     AS (SELECT N,
                NewGrp = CASE WHEN N = 1 + LAG(N) OVER (ORDER BY N) THEN 0 ELSE 1 END
         FROM   N
         WHERE  NOT EXISTS (SELECT *
                            FROM   #intervals
                            WHERE  N BETWEEN [from] AND [to])),
     T2
     AS (SELECT N,
                Grp = SUM(NewGrp) OVER (ORDER BY N ROWS UNBOUNDED PRECEDING) 
         FROM   T1)
SELECT MIN(N),
       MAX(N)
FROM   T2
GROUP  BY Grp
OPTION (MAXRECURSION 10000) 

通过使用永久数字表而不是递归CTE,您可以简化事情并提高效率