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

后端 未结 5 1828
醉话见心
醉话见心 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:18

    I think you're essentially interested in where the 'Name' changes from one record to the next (in order of 'Time'). If you can identify where this happens you can generate your desired output.

    Since you mentioned CTEs I'm going to assume you're on SQL Server 2005+ and can therefore use the ROW_NUMBER() function. You can use ROW_NUMBER() as a handy way to identify consecutive pairs of records and then to find those where the 'Name' changes.

    How about this:

    WITH OrderedTable AS
    (
        SELECT
            *,
            ROW_NUMBER() OVER (ORDER BY Time) AS Ordinal
        FROM
            [YourTable]
    ),
    NameChange AS
    (
        SELECT
            after.Time AS Time,
            after.Name AS Name,
            ROW_NUMBER() OVER (ORDER BY after.Time) AS Ordinal
        FROM
            OrderedTable before
            RIGHT JOIN OrderedTable after ON after.Ordinal = before.Ordinal + 1
        WHERE
            ISNULL(before.Name, '') <> after.Name
    )
    
    SELECT
        before.Time AS FromTime,
        after.Time AS ToTime,
        before.Name
    FROM
        NameChange before
        LEFT JOIN NameChange after ON after.Ordinal = before.Ordinal + 1
    

提交回复
热议问题