Find missing time intervals in a table

后端 未结 1 654
感动是毒
感动是毒 2021-02-09 19:28

I have the following table which contains values read every 15 minutes from several different devices:

ID   DeviceID   Date                    Value
------------         


        
相关标签:
1条回答
  • 2021-02-09 19:54

    Following should work and doesn't return just a single record for a deviceid.

    The gist of this is to

    • Add a rownumber to each record, ordered by Date and restarting for each DeviceID.
    • Join with self to create a result with rows consisting of the combination of two original rows. The relation between the columns of each row is the rownumber (+1) and the DeviceID.
    • Only retain those rows where the related Date is more than 15 minutes.

    SQL Statement

    ;WITH t AS (
      SELECT  *, rn = ROW_NUMBER() OVER (PARTITION BY DeviceID ORDER BY Date)
      FROM    TestTable
    )  
    SELECT  t1.DeviceID, t1.Date, t2.Date
    FROM    t t1
            INNER JOIN t t2 ON t2.DeviceID = t1.DeviceID AND t2.rn = t1.rn + 1
    WHERE   DATEDIFF(MINUTE, t1.Date, t2.Date) > 15        
    

    Test script

    ;WITH TestTable (ID, DeviceID, Date, Value) AS (
      SELECT 1, 3, '2011-08-24 00:00:00', 0.51 UNION ALL
      SELECT 2, 3, '2011-08-24 00:15:00', 2.9 UNION ALL
      SELECT 3, 3, '2011-08-24 00:30:00', 0 UNION ALL
      SELECT 4, 3, '2011-08-24 00:45:00', 7.1 UNION ALL
      SELECT 5, 3, '2011-08-24 01:00:00', 1.05 UNION ALL
      SELECT 6, 3, '2011-08-24 03:15:00', 3.8 
    )
    , t AS (
      SELECT  *, rn = ROW_NUMBER() OVER (PARTITION BY DeviceID ORDER BY Date)
      FROM    TestTable
    )  
    SELECT  t1.DeviceID, t1.Date, t2.Date
    FROM    t t1
            INNER JOIN t t2 ON t2.DeviceID = t1.DeviceID AND t2.rn = t1.rn + 1
    WHERE   DATEDIFF(MINUTE, t1.Date, t2.Date) > 15        
    
    0 讨论(0)
提交回复
热议问题