SELECT MIN(col1) AS start_range, MAX(col1) AS end_range
FROM (SELECT col1,
(
SELECT MIN(B.col1)
FROM dbo.T1 AS B
WHERE B.col1 >= A.col1
AND NOT EXISTS
(SELECT *
FROM dbo.T1 AS C
WHERE C.col1 = B.col1 + 1)
) AS grp
FROM dbo.T1 AS A) AS jh
GROUP BY grp;
如果我删除“AS jh”,为什么会出现错误?以及为什么我需要相同的“AS grp”。(不一样,因为我分组)但我不能删除它。在第二个代码中没有这样的“AS”。
SELECT col1,
(SELECT MIN(B.col1)
FROM dbo.T1 AS B
WHERE B.col1 >= A.col1
-- is this row the last in its group?
AND NOT EXISTS
(SELECT *
FROM dbo.T1 AS C
WHERE C.col1 = B.col1 + 1)) FROM dbo.T1 AS A;
第三个代码:
SELECT MIN(col1) AS start_range, MAX(col1) AS end_range
FROM (SELECT col1,
-- the difference is constant and unique per island
col1 - ROW_NUMBER() OVER(ORDER BY col1) AS grp
FROM dbo.T1) AS D
GROUP BY grp;
这个怎么运作?它显示与第一个代码相同的结果。我理解第二个和第四个代码。但我真的不能理解第三。我对第一个的理解是一半。那(第三个)是如何工作的?第四:
SELECT col1, col1 - ROW_NUMBER() OVER(ORDER BY col1) AS diff
FROM dbo.T1;