如何从MSSQL中的许多间隔值获取第一个和最后一个记录

时间:2013-03-13 11:07:07

标签: sql sql-server range intervals min

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

id | 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

我一直在寻找解决方案,但直到现在我找不到任何东西,任何帮助都会受到赞赏。

由于

1 个答案:

答案 0 :(得分:0)

这种解决方案可以是一种选择。但请注意,WITH构造具有递归深度的限制。 Maximium递归大小可以增加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