【问题标题】:In Microsoft SQL or Tableau, how to find the overlapping time of the data?在 Microsoft SQL 或 Tableau 中,如何找到数据的重叠时间?
【发布时间】:2018-09-28 03:44:39
【问题描述】:

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

附件是重叠时间的图片和我想要的输出。有什么方法可以通过排除 Microsoft MSQL 或 Tableau 中的重叠数据来找到实际的停机时间?

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

Original Data

Desired Output

【问题讨论】:

  • 以文本格式而不是图像添加数据,并提及预期输出。
  • 让我们考虑一下。首先,您应该已经提供了预期的输出(以可消耗的格式)。您的样本似乎有一个重叠 - 前 2 行。正确的?这里的逻辑是否基于具有相同 TimeStarted 值的多行?还是更复杂?不要基于查看几行来做出假设——这可能会产生很大的误导。您可能想搜索“间隙和孤岛”,因为这可能是该常用逻辑的简单版本。

标签: sql-server tableau-api


【解决方案1】:

下面的代码查找具有重叠的条目并将重叠切分成离散的时间块。联合删除重复的时间块。使用此代码,答案是 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

【讨论】:

  • 感谢您的帮助。如果我希望我的结果以他的方式显示怎么办。我该怎么做? i.stack.imgur.com/UxYKJ.jpg
  • @Felix,您需要添加一个 Machine 列并将 JOIN 条件扩展到“... and a.id b.id AND a.machine = b.machine”。还要将 Machine 添加到 UNION 中的每个 SELECT 中。生产线可能来自机器的相关表 - 加入该表以获得生产线。查询已经给出了 TimeStarted、TimeCompleted。您可以使用 DATEDIFF 计算停机时间(小时),如查询中所示 - 将 ss 更改为 hh(小时)。但是请注意,停机时间可能不是连续的,因此您可以为每台机器设置 >1 行。不确定最后一列是什么——它可能已经跑题了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2022-12-04
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多