您能否尝试使用更多数据执行 SQL 查询
请尝试为不同的流程创建示例数据
此查询汇总按进程分组的停机时间,您可以从聚合 SELECT 语句(这是最后一个查询)中删除进程以计算总体停机时间。甚至将 GroupId 添加到每个重叠停机时间链的停机时间列表中
请查看关于重叠时间段的 SQL 查询的SQL 教程,其中详细解释了解决方案
;with rawdata as (
select
Process, id, StartTime, EndTime,
ROW_NUMBER() over (partition by Process order by StartTime, EndTime) as rn
from Processes
), cte as (
select
Process, StartTime, EndTime, rn, 1 as GroupId
from rawdata
where rn = 1
union all
select
p1.Process,
case
when (p1.starttime between p2.starttime and p2.endtime) then p2.starttime
when (p2.starttime between p1.starttime and p1.endtime) then p1.starttime
when (p1.starttime < p2.starttime and p1.endtime > p2.endtime) then p1.starttime
when (p1.starttime > p2.starttime and p1.endtime < p2.endtime) then p2.starttime
else p2.starttime
end as StartTime,
case
when (p1.EndTime between p2.starttime and p2.endtime) then p2.EndTime
when (p2.endtime between p1.starttime and p1.endtime) then p1.endtime
when (p1.starttime < p2.starttime and p1.endtime > p2.endtime) then p1.endtime
when (p1.starttime > p2.starttime and p1.endtime < p2.endtime) then p2.endtime
else p2.endtime
end as EndTime,
p2.rn,
case when
(p1.starttime between p2.starttime and p2.endtime) or
(p1.endtime between p2.starttime and p2.endtime) or
(p1.starttime < p2.starttime and p1.endtime > p2.endtime) or
(p1.starttime > p2.starttime and p1.endtime < p2.endtime)
then
p1.GroupId
else
(p1.GroupId+1)
end as GroupId
from cte p1
inner join rawdata p2
on p1.Process = p2.Process and
(p1.rn+1) = p2.rn
)
select
Process,
sum(datediff(second, StartTime, EndTime)) totalDownTime
from (
select
Process, GroupId, min(StartTime) StartTime, max(EndTime) EndTime
from cte
group by Process, GroupId
) t
group by Process
输出如下

希望有用,