计算日志记录表中的持续时间和组连续时间戳

时间:2013-06-14 00:18:54

标签: sql sql-server-2008 tsql

我正在尝试计算每两分钟检查一次的日志表的持续时间,如果有任何警报则会输入它们。过度简化的表格格式如下:

RuleID   TimeStamp  
1        2013-04-10 08:40
1        2013-04-10 08:42
1        2013-04-10 08:44
2        2013-04-10 08:40
2        2013-04-10 08:42
1        2013-04-10 09:40
1        2013-04-10 09:42

我要找的结果如下:

RuleID   EarliestTimeStamp   LatestTimeStamp   DurationInMins
1        2013-04-10 08:40    2013-04-10 08:44  4
2        2013-04-10 08:40    2013-04-10 08:42  2
1        2013-04-10 09:40    2013-04-10 09:42  2

正如您所见,规则可以在整个过程中多次记录,如果中断超过两分钟,则会将其视为新事件,并且是新的结果条目。

如果需要,我可以提供更多详细信息,遗憾的是,我无法提供我的数据集。

2 个答案:

答案 0 :(得分:0)

感谢周五下午的大脑锻炼。以下是我的想法:

;WITH s AS
(SELECT t1.RuleID, t1.TimeStamp AS StartTime from Table1 t1
LEFT JOIN Table1 t2 ON
t1.RuleID = t2.RuleID and dateadd(minute, 2, t2.TimeStamp) = t1.TimeStamp
WHERE t2.TimeStamp IS NULL)
,e AS
(SELECT t1.RuleID, t1.TimeStamp AS EndTime from Table1 t1
LEFT JOIN Table1 t2 ON
t1.RuleID = t2.RuleID and dateadd(minute, -2, t2.TimeStamp) = t1.TimeStamp
WHERE t2.TimeStamp IS NULL)
SELECT s.RuleID, s.StartTime, e1.EndTime, datediff(minute, s.StartTime, e1.EndTime) AS DiffInMins FROM s INNER JOIN e AS e1
ON s.RuleID = e1.RuleID AND s.StartTime < e1.EndTime
AND e1.EndTime = (SELECT MIN(EndTime) FROM e AS e2 WHERE e2.RuleID = e1.RuleID AND s.StartTime < e2.EndTime)

结果如下:

| RULEID |                    STARTTIME |                      ENDTIME | DIFFINMINS |
-------------------------------------------------------------------------------------
|      1 | April, 10 2013 08:40:00+0000 | April, 10 2013 08:44:00+0000 |          4 |
|      2 | April, 10 2013 08:40:00+0000 | April, 10 2013 08:42:00+0000 |          2 |
|      1 | April, 10 2013 09:40:00+0000 | April, 10 2013 09:42:00+0000 |          2 |

SQL Fiddle

答案 1 :(得分:0)

declare @Table1 table
    ([RuleID] int, [TimeStamp] smalldatetime)
;

INSERT INTO @Table1
    ([RuleID], [TimeStamp])
VALUES
    (1, '2013-04-10 08:40'),
    (1, '2013-04-10 08:42'),
    (1, '2013-04-10 08:44'),
    (2, '2013-04-10 08:40'),
    (2, '2013-04-10 08:42'),
    (1, '2013-04-10 09:40'),
    (1, '2013-04-10 09:42')
;

select distinct t1.RuleID, t1.Timestamp EarliestTimeStamp,a.LatestTimeStamp, datediff(minute, t1.Timestamp, a.LatestTimeStamp) DurationInMins 
from @Table1 t1
outer apply
(select min(timestamp) LatestTimeStamp from @Table1 t2 
where t1.timestamp <= timestamp and t1.ruleid = ruleid and not exists (select 1 from @table1 where t1.ruleid = ruleid and timestamp > t1.timestamp and timestamp > t2.timestamp and timestamp <= dateadd(minute, 2, t2.timestamp)))a
where not exists(select 1 from @Table1 where timestamp < t1.timestamp and timestamp >= dateadd(minute,-2,t1.timestamp)
and t1.RuleId = RuleId)