Detect Anomaly Intervals with SQL

后端 未结 4 1427
猫巷女王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:07

    This has to be one of the harder questions I've seen today - thanks! I assume you can use CTEs? If so, try something like this:

    ;WITH Filtered
    AS
    (
        SELECT ROW_NUMBER() OVER (ORDER BY dateField) RN, dateField, Status
        FROM Test    
    )
    SELECT F1.RN, F3.MinRN,
        F1.dateField StartDate,
        F2.dateField Enddate
    FROM Filtered      F1, Filtered F2, (
    SELECT F1a.RN, MIN(F3a.RN) as MinRN
    FROM Filtered      F1a
       JOIN Filtered F2a ON F1a.RN = F2a.RN+1 AND F1a.Status = 2 AND F2a.Status <> 2
       JOIN Filtered F3a ON F1a.RN < F3a.RN AND F3a.Status <> 2
    GROUP BY F1a.RN ) F3 
    WHERE F1.RN = F3.RN AND F2.RN = F3.MinRN
    

    And the Fiddle. I didn't add the intervals, but I imagine you can handle that part from here.

    Good luck.

提交回复
热议问题