如何在SQL中减去数值范围?
例如:
SELECT 01 AS 'BEGIN', 99 AS 'END'
EXCEPT
SELECT 01 AS 'BEGIN', 15 AS 'END'
预期结果:
16 AS 'BEGIN', 99 AS 'END'
更完整的例子:
COMPLETE
BEGIN ---- END
01 99
EXTRACT
BEGIN ---- END
15 30
RESULT
BEGIN ---- END
01 14
31 99
可能吗?
答案 0 :(得分:2)
试试这个:
;WITH Complete AS (
SELECT 1 AS [BEGIN], 99 AS [END]
), Extract AS (
SELECT 1 AS [BEGIN], 15 AS [END]
), FreeSpace AS (
SELECT (SELECT [BEGIN] - 1 FROM Extract) AS [LEFT],
(SELECT [END] + 1 FROM Extract) AS [RIGHT]
)
SELECT [BEGIN], [END]
FROM (
SELECT [BEGIN], (SELECT [LEFT] FROM FreeSpace) AS [END]
FROM Complete
UNION ALL
SELECT (SELECT [RIGHT] FROM FreeSpace) AS [BEGIN], [END]
FROM Complete ) AS t
WHERE [END] >= [BEGIN]
CTE描述:
Complete
是我们希望减去另一个间隔Extract
是从Complete
FreeSpace
包含Extract
示例:强>
Extract: 15----------30
14 31
FreeSpace: <------| |------------->
使用14
中的值31
和FreeSpace
构建Extract
左侧和右侧的两个可能的非重叠区间。
谓词:
WHERE [END] >= [BEGIN]
最后检查这两个区间是否真的存在。