在Microsoft SQL或Tableau中,如何查找数据的重叠时间?

时间:2018-04-18 03:12:57

标签: sql-server tableau

我正在学校开展一个项目,它要求我找到生产线内所有机器的实际停机时间。

附上的是我想要的重叠时间和所需输出的图片。有没有办法通过排除Microsoft MSQL或Tableau中的重叠数据来找到实际的停机时间?

实际停机时间=停机总时间 - 重叠停机时间。谢谢!

Original Data

Desired Output

1 个答案:

答案 0 :(得分:0)

下面的代码查找具有重叠的条目,并将重叠切入到离散的时间块中。联合删除重复的时间块。使用此代码,答案是24955秒的停机时间。

create table #t1 (TimeStarted datetime, TimeCompleted datetime, id integer)
insert into #t1 values ('20180416 12 am', '20180416 2:02:21am', 1211958)
...
;
with overlap_cte
as
(
select a.*, 
   case when b.timestarted >= a.timestarted then b.timestarted else a.timestarted end as overlapstart, 
   case when b.timecompleted <= a.timecompleted then b.timecompleted else a.timecompleted end as overlapend
from #t1 a
   inner join #t1 b on (b.timestarted between a.timestarted and a.timecompleted or b.timecompleted between a.timestarted and a.timecompleted) and a.id <> b.id
),
unique_downtime_cte
as
(
select timestarted, overlapstart as timecompleted from overlap_cte where timestarted <> overlapstart
union
select overlapend, timecompleted from overlap_cte where overlapend <> timecompleted
union
select overlapstart, overlapend from overlap_cte
union
select timestarted, timecompleted from #t1 where id not in (select id from overlap_cte)
)
select *, datediff(ss, timestarted, timecompleted) as downtime_seconds from unique_downtime_cte