How Can I Detect and Bound Changes Between Row Values in a SQL Table?

后端 未结 5 1806
醉话见心
醉话见心 2020-12-01 06:39

I have a table which records values over time, similar to the following:

RecordId  Time   Name
========================
1         10     Running
2         18         


        
5条回答
  •  春和景丽
    2020-12-01 07:14

    Here's a CTE solution that gets the results you're seeking:

    ;WITH TheRecords (FirstTime,SecondTime,[Name])
    AS
    (
        SELECT [Time],
        (
            SELECT MIN([Time]) 
            FROM ActivityTable at2
            WHERE at2.[Time]>at.[Time]
            AND at2.[Name]<>at.[Name]
        ),
        [Name]
        FROM ActivityTable at
    )
    SELECT MIN(FirstTime) AS FromTime,SecondTime AS ToTime,MIN([Name]) AS [Name]
    FROM TheRecords
    GROUP BY SecondTime
    ORDER BY FromTime,ToTime
    

提交回复
热议问题