这样的解决方案可以是一种选择。但请注意 WITH 构造具有递归深度的限制。最大递归大小可以增加 200。OPTION (MAXRECURSION 200)
DECLARE @MyTable TABLE (Iteration INT, Label VARCHAR(50))
INSERT INTO @MyTable(Iteration, Label)
VALUES
(1, 'A1'),
(2, 'A2'),
(3, 'A3'),
(4, 'A4'),
(5, 'A10'),
(6, 'A11'),
(7, 'A13')
DECLARE @RefinedTable TABLE (LabelId INT, Label VARCHAR(50))
INSERT INTO @RefinedTable(LabelId, Label)
SELECT CAST(REPLACE(Label, 'A', '') AS INT) AS LabelNo, Label
FROM @MyTable
DECLARE @Queue TABLE (Parent VARCHAR(50), Child VARCHAR(50))
INSERT INTO @Queue(Parent, Child)
SELECT t1.Label, t2.Label
FROM @RefinedTable t1
LEFT OUTER JOIN @RefinedTable t2
ON t1.LabelId + 1 = t2.LabelId;
WITH Checker(Parent, Child, LastItem, Depth)
AS
(
SELECT Parent, CAST(NULL AS VARCHAR(50)), Parent, 0
FROM @Queue
WHERE Child IS NULL
UNION ALL
SELECT q.Parent, q.Child, c.LastItem, c.Depth + 1
FROM @Queue q
INNER JOIN Checker c
ON c.Parent = q.Child
)
SELECT
'A' + CAST(CAST(REPLACE(LastItem, 'A', '') AS INT) - MAX(Depth) AS VARCHAR) StartLabel,
LastItem EndLabel,
COUNT(*) AS [Count]
FROM Checker
GROUP BY LastItem
ORDER BY 1