[英]Subtract one number range from another
I have number interval from X to Y (for example x = 100, y = 200, so interval is 100, 101, ... 200) and have table with two columns "from" and "two", wich means another intervals, like 我有一个从X到Y的数字区间(例如x = 100,y = 200,所以区间是100、101,... 200),并且表格中有两列“ from”和“ two”,这意味着另一个区间,喜欢
from to
110 120
130 140
I need to subtract from range (x,y) all ranges in table (from, to). 我需要从范围(x,y)中减去表中的所有范围(从,到)。 So, the resul will
因此,结果将
100 109
121 129
141 200
Is it possible? 可能吗?
One way would be ( DEMO ) 一种方法是( 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)
You could simplify things and make it a bit more efficient by using a permanent numbers table instead of a recursive CTE 您可以使用永久数字表而不是递归CTE来简化事情并使其更有效率
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.