计算重叠分钟数

时间:2017-10-09 12:35:27

标签: sql sql-server

Start,                  Stop,                   Machine,   Prodid
2017-09-11 06:36:37.000 2017-09-11 07:41:35.000 CNC M 6 17-012811
2017-09-11 07:49:27.000 2017-09-11 10:10:01.000 CNC M 6 17-012811
2017-09-11 09:34:46.000 2017-09-11 10:10:01.000 CNC M 7 17-012738
2017-09-11 10:14:50.000 2017-09-11 11:50:15.000 CNC M 6 17-012811
2017-09-11 10:15:50.000 2017-09-11 11:50:15.000 CNC M 7 17-012738
2017-09-11 11:55:52.000 2017-09-11 12:17:03.000 CNC M 6 17-012811
2017-09-11 11:56:15.000 2017-09-11 12:17:14.000 CNC M 7 17-012738

我需要以分钟计算重叠机器运行时间的数量。有必要这样做吗?有滞后还是铅? 或者我用子查询做到了吗?我在SQL Server 2016上工作。

1 个答案:

答案 0 :(得分:1)

您可以使用此查询。我从停止时间中减去重叠的开始时间。

DECLARE @Tbl TABLE(Start DATETIME, [Stop] DATETIME,Machine VARCHAR(20),Prodid VARCHAR(20))

INSERT INTO @Tbl VALUES

('2017-09-11 06:36:37.000','2017-09-11 07:41:35.000','CNC M 6','17-012811'),
('2017-09-11 07:49:27.000','2017-09-11 10:10:01.000','CNC M 6','17-012811'),
('2017-09-11 09:34:46.000','2017-09-11 10:10:01.000','CNC M 7','17-012738'),
('2017-09-11 10:14:50.000','2017-09-11 11:50:15.000','CNC M 6','17-012811'),
('2017-09-11 10:15:50.000','2017-09-11 11:50:15.000','CNC M 7','17-012738'),
('2017-09-11 11:55:52.000','2017-09-11 12:17:03.000','CNC M 6','17-012811'),
('2017-09-11 11:56:15.000','2017-09-11 12:17:14.000','CNC M 7','17-012738')

SELECT T1.*, DATEDIFF(MINUTE, Ovr.Start , T1.[Stop])  Overlapping FROM @Tbl T1
OUTER APPLY (SELECT TOP 1 * FROM @Tbl T2 WHERE T2.Start > T1.Start AND T2.Start < T1.Stop ORDER BY T2.Start) ) AS Ovr

结果

Start                   Stop                    Machine              Prodid               Overlapping
----------------------- ----------------------- -------------------- -------------------- -----------
2017-09-11 06:36:37.000 2017-09-11 07:41:35.000 CNC M 6              17-012811            NULL
2017-09-11 07:49:27.000 2017-09-11 10:10:01.000 CNC M 6              17-012811            36
2017-09-11 09:34:46.000 2017-09-11 10:10:01.000 CNC M 7              17-012738            NULL
2017-09-11 10:14:50.000 2017-09-11 11:50:15.000 CNC M 6              17-012811            95
2017-09-11 10:15:50.000 2017-09-11 11:50:15.000 CNC M 7              17-012738            NULL
2017-09-11 11:55:52.000 2017-09-11 12:17:03.000 CNC M 6              17-012811            21
2017-09-11 11:56:15.000 2017-09-11 12:17:14.000 CNC M 7              17-012738            NULL