0

我需要为 MSSQL 创建一个查询,以仅获取 MSSQL 表中每个间隔的第一条和最后一条记录。例如我有下表

编号 | label_id

1 | A1

2 | A2

3 | A3

4 | A4

5 | A10

6 | A11

7 | A13

结果必须显示类似

label_id_start | label_id_start | 数数

A1         |       A4          |   4
A10        |       A11         |   2
A13        |       A13         |   1

我一直在寻找解决方案,但到目前为止我找不到任何东西,任何帮助将不胜感激。

谢谢

4

1 回答 1

0

这样的解决方案可以是一种选择。但请注意 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
于 2013-03-13T12:58:22.647 回答