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

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

    This will not work in SQL Server 2008, only in SQL Server 2012 version that has the LAG() and LEAD() analytic functions, but I'll leave it here for anyone with newer versions:

    SELECT Time AS FromTime
         , LEAD(Time) OVER (ORDER BY Time) AS ToTime
         , Name
    FROM
      ( SELECT Time 
             , LAG(Name) OVER (ORDER BY Time) AS PreviousName
             , Name
        FROM Data  
      ) AS tmp
    WHERE PreviousName <> Name 
       OR PreviousName IS NULL ;
    

    Tested in SQL-Fiddle

    With an index on (Time, Name) it will need an index scan.

    Edit:

    If NULL is a valid value for Name that needs to be taken as a valid entry, use the following WHERE clause:

    WHERE PreviousName <> Name 
       OR (PreviousName IS NULL AND Name IS NOT NULL)
       OR (PreviousName IS NOT NULL AND Name IS NULL) ;
    

提交回复
热议问题