这是相对可移植的 SQL 解决方案,因为您没有指定数据库
Create Table SampleData (Location int, Number Int)
INSERT INTO SampleData VALUES (300, 15)
INSERT INTO SampleData VALUES (300, 16)
INSERT INTO SampleData VALUES (300, 17)
INSERT INTO SampleData VALUES (300, 18)
INSERT INTO SampleData VALUES (300, 21)
INSERT INTO SampleData VALUES (300, 22)
INSERT INTO SampleData VALUES (300, 23)
INSERT INTO SampleData VALUES (400, 10)
INSERT INTO SampleData VALUES (400, 11)
INSERT INTO SampleData VALUES (400, 14)
INSERT INTO SampleData VALUES (400, 16)
SELECT
t1.Location,
t1.Number AS startofgroup,
MIN(t2.Number) AS endofgroup
FROM (SELECT Number , Location
FROM SampleData tbl1
WHERE NOT EXISTS(SELECT *
FROM SampleData tbl2
WHERE tbl1.Number - tbl2.Number = 1
and tbl1.Location = tbl2.Location)) t1
INNER JOIN (SELECT Number , Location
FROM SampleData tbl1
WHERE NOT EXISTS(SELECT *
FROM SampleData tbl2
WHERE tbl2.Number - tbl1.Number = 1
and tbl1.Location = tbl2.Location)) t2
ON t1.Number <= t2.Number
and t1.Location = t2.Location
GROUP BY
t1.Location,
t1.Number
ORDER BY
Location,
startofgroup
输出
Location startofgroup endofgroup
----------- ------------ -----------
300 15 18
300 21 23
400 10 11
400 14 14
400 16 16
它是清单 2 的修改版本。用于识别岛屿的基于集合的解决方案。亚历山大·科扎克(Alexander Kozak )的序数中的岛屿和间隙
如果您正在寻找 SQL Server 2005 及更高版本的更多选项,您应该搜索短语“ Itzik Ben-Gan gaps and island ”