Detect Anomaly Intervals with SQL

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

    Just for the sake of having an alternative. Tried to do some test on performance, but did not finish.

    SELECT
      MIN([main].[Start]) AS [Start],
      [main].[End],
      DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Seconds]
    FROM
    (
      SELECT
        [sub].[Start],
        MIN([sub].[End]) AS [End]
      FROM
      (
        SELECT
          [start].[Timestamp] AS [Start],
          [start].[Status] AS [StartingStatus],
          [end].[Timestamp] AS [End],
          [end].[Status] AS [EndingStatus]
        FROM [Alerts] [start],  [Alerts] [end]
        WHERE [start].[Status] = 2 
          AND [start].[Timestamp] < [end].[Timestamp]
          AND [start].[Status] <> [end].[Status]
      ) AS [sub]
      GROUP BY
        [sub].[Start],
        [sub].[StartingStatus]
    ) AS [main]
    GROUP BY
      [main].[End]
    

    And here is a Fiddle.

提交回复
热议问题