Detect Anomaly Intervals with SQL

后端 未结 4 1243
猫巷女王i
猫巷女王i 2021-02-06 11:26

My problem is simple: I have a table with a series of statuses and timestamps (for the sake of curiosity, these statuses indicate alarm levels) and I would like to query this ta

4条回答
  •  悲&欢浪女
    2021-02-06 12:21

    Finally figured out a version I was happy with. It took me remembering an answer from another question (can't remember which one though) where it was pointed out that the difference between two (increasing) sequences was always a constant.

    WITH Ordered (occurredAt, status, row, grp) 
                 as (SELECT occurredAt, status, 
                            ROW_NUMBER() OVER (ORDER BY occurredat), 
                            ROW_NUMBER() OVER (PARTITION BY status 
                                               ORDER BY occurredat)
                     FROM Alert)
    
    SELECT Event.startDate, Ending.occurredAt as endDate,
           DATEDIFF(second, Event.startDate, Ending.occurredAt) as interval
    
    FROM (SELECT MIN(occurredAt) as startDate, MAX(row) as ending
          FROM Ordered
          WHERE status = 2
          GROUP BY row - grp) Event
    
    LEFT JOIN (SELECT occurredAt, row
               FROM Ordered
               WHERE status != 2) Ending
            ON Event.ending + 1 = Ending.row
    

    (working SQL Fiddle example, with some additional data rows for work checking).

    This unfortunately doesn't correctly deal with level-2 statuses that are end rows (behavior unspecified), although it does list them.

提交回复
热议问题