1

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

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

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

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

4

2 回答 2

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)
于 2013-06-14T08:23:32.473 回答
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小提琴

于 2013-06-14T04:13:11.803 回答