如何减去SQL中的数值范围?

时间:2015-12-21 21:18:34

标签: sql asp.net .net sql-server

如何在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 

可能吗?

1 个答案:

答案 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]

Demo here

CTE描述:

  • Complete是我们希望减去另一个间隔
  • 的间隔
  • Extract是从Complete
  • 中提取的时间间隔
  • FreeSpace包含Extract
  • 左侧和右侧的'免费' 边界

示例:

Extract:            15----------30
                  14              31  
FreeSpace: <------|               |------------->

使用14中的值31FreeSpace构建Extract左侧和右侧的两个可能的非重叠区间。

谓词:

WHERE [END] >= [BEGIN]

最后检查这两个区间是否真的存在。