不选择底行

时间:2013-01-30 03:09:30

标签: sql sql-server sql-server-2005

我有LINK

为什么直到最后一行才计算?

我想要直到最后一行的输出。
它计算 STATUS = 0

的间隔
    CREATE TABLE [Alerts]
(
  [Timestamp] datetime,
  [Status] int
)

INSERT INTO [Alerts] ([Timestamp], [Status])
  VALUES
    ('2013-1-1 00:00:00', 1),
    ('2013-1-1 00:00:05', 1),
    ('2013-1-1 00:00:10', 2),
    ('2013-1-1 00:00:15', 2),
    ('2013-1-1 00:00:20', 0),
    ('2013-1-1 00:00:25', 1),
    ('2013-1-1 00:00:30', 1),
    ('2013-1-1 00:00:32', 2),
    ('2013-1-1 00:00:35', 2),
    ('2013-1-1 00:00:40', 0),
    ('2013-1-1 00:00:45', 0),
    ('2013-1-1 00:00:50', 0)



我试过这个:

SELECT
  MIN ([main].[Start]) AS [STOP_Begin],
  [main].[End] AS [STOP_End],
  DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Interval_Second]
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] = 0
      AND [start].[Timestamp] < [end].[Timestamp]
      AND [start].[Status] <> [end].[Status]
  ) AS [sub]
  GROUP BY
    [sub].[Start],
    [sub].[StartingStatus]
) AS [main]
GROUP BY
  [main].[End]



它给出了输出:
OUTPUT

我希望输出计数到最后一行,如果 0 是它给我的最后一行 Interval = NULL ,我的问题直到最后一行才计算其中 0 那里



我想要的结果:

 ---------STOP_BEGIN-----         --------STOP_END--------- ----INTERVAL_SECOND-----<br />
January, 01 2013 00:00:20+0000  January, 01 2013 00:00:25+0000      5
January, 01 2013 00:00:40+0000           NULL                       NULL

1 个答案:

答案 0 :(得分:1)

这是您的查询(我已将其添加到您的底部的SQL Fiddle)

SELECT
  MIN ([main].[Start]) AS [STOP_Begin],
  [main].[End] AS [STOP_End],
  DATEDIFF(s, MIN([main].[Start]), [main].[End]) AS [Interval_Second]
FROM
(
  SELECT
    [starts].[Start],
    MIN([ends].[Timestamp]) AS [End]
  FROM
  (
    SELECT
      [Timestamp] AS [Start]
    FROM [Alerts]
    WHERE [Status] = 0
  ) AS [starts] LEFT JOIN [Alerts] AS [ends]
  ON  [starts].[Start] < [ends].[Timestamp]
  AND [ends].[Status] <> 0
  GROUP BY
    [starts].[Start]
) AS [main]
GROUP BY
  [main].[End]
ORDER BY 1