Sql 前十名活动持续时间
我有一个SQL Server表,如下所示:Sql 前十名活动持续时间,sql,sql-server,sql-server-2008,select,Sql,Sql Server,Sql Server 2008,Select,我有一个SQL Server表,如下所示: TimeStamp (datetime)| Alarm (string) | Active (bool) 01.08.2013 1:30:05 | Alarm 1 | false 01.08.2013 1:29:54 | Alarm 2 | true 01.08.2013 1:28:43 | Alarm 1 | true 01.08.2013 1:27:21
TimeStamp (datetime)| Alarm (string) | Active (bool)
01.08.2013 1:30:05 | Alarm 1 | false
01.08.2013 1:29:54 | Alarm 2 | true
01.08.2013 1:28:43 | Alarm 1 | true
01.08.2013 1:27:21 | Alarm 3 | false
01.08.2013 1:26:35 | Alarm 1 | false
01.08.2013 1:25:34 | Alarm 1 | true
我已经显示了前10个报警事件:
SELECT TOP 10 Alarm, COUNT(Alarm) AS Occurrence
FROM MyTable
WHERE (Active = 'True')
GROUP BY Alarm
ORDER BY Occurrence DESC
我现在需要前10个警报持续时间
目标是获得每个报警的持续时间总和(从true到false)
我真的被阻止了,我想我需要迭代每一行并为每个met报警求和时间值
但我不知道如何使用SQL查询来实现这一点。任何帮助或指导都将不胜感激
提前谢谢
@Roman Pekar:SQL server 2008 @Gordon Linoff:预期输出=>前10个报警持续时间(当报警为真时))
您可以使用
交叉应用
查找打开
后的第一个关闭
:
select top 10 active.Alarm
, active.TimeStamp as TimeOn
, active.TimeStamp as TimeOff
, datediff(second, active.TimeStamp, inactive.TimeStamp) as Duration
from YourTable active
cross apply
(
select top 1 *
from YourTable inactive
where inactive.Active = 'false'
and inactive.Alarm = active.Alarm
and inactive.TimeStamp > active.TimeStamp
order by
inactive.TimeStamp
) inactive
where active.Active = 'true'
order by
Duration desc
这里是另一个可能更有效的解决方案
;with a as
(
select a.Alarm
, a.Active
, a.[Timestamp]
, Sequence = dense_rank() over
(
partition by a.Alarm, a.Active
order by a.[TimeStamp]
)
from #YourTable a
),
b as
(
select a.Alarm
, Start = b.[Timestamp]
, Stop = a.[Timestamp]
from a
left outer join a b
on b.Alarm = a.Alarm
and b.Sequence = a.Sequence
and b.Active = 'true'
where a.Active = 'false'
)
select b.Alarm
, DurationMinutes = sum(datediff(millisecond, b.Start, b.Stop) / 1000.0 / 60.0)
from b
group by b.Alarm
您有什么版本的SQL Server?请提供示例输出。不清楚您希望问题中数据的结果是什么。由于报警2和报警3只出现一次(报警2=1真,报警3=1假),您如何计算报警2和报警3的时间?另外,对于报警1,您需要两行还是只需要一行。我的意思是,你想计算总持续时间或两者的持续时间,1:25:34到1:26:35,然后1:28:43到1:30:05?非常感谢你的回答,这对我帮助很大!可能更高效,但也要求更高的数据一致性。如果第一行是前一个报警的结尾(“关闭”条目),则查询将返回负持续时间。@Andomar True。您可以在“on”子句中添加“and b.Timestamp
;with a as
(
select a.Alarm
, a.Active
, a.[Timestamp]
, Sequence = dense_rank() over
(
partition by a.Alarm, a.Active
order by a.[TimeStamp]
)
from #YourTable a
),
b as
(
select a.Alarm
, Start = b.[Timestamp]
, Stop = a.[Timestamp]
from a
left outer join a b
on b.Alarm = a.Alarm
and b.Sequence = a.Sequence
and b.Active = 'true'
where a.Active = 'false'
)
select b.Alarm
, DurationMinutes = sum(datediff(millisecond, b.Start, b.Stop) / 1000.0 / 60.0)
from b
group by b.Alarm