Hi.
Thanks for looking at my challenge.
The challenge is to compute total duration of service jobs for a work center given individual job start/finish times. Jobs may overlap.
DECLARE @CalendarEvents TABLE
(
wrcID int NOT NULL -- work center
,jobID int NOT NULL -- job to perform
-- calendar
,ceStartDateTime datetimeoffset(0) NOT NULL
,ceFinishDateTime datetimeoffset(0) NOT NULL
,PRIMARY KEY(wrcID, jobID)
)
INSERT INTO @CalendarEvents
VALUES
(1, 1, '2021-05-26 08:00:00.0000000 -05:00', '2021-05-26 08:30:00.0000000 -05:00')
,(1, 2, '2021-05-26 08:30:00.0000000 -05:00', '2021-05-26 09:00:00.0000000 -05:00')
,(1, 3, '2021-05-26 09:10:00.0000000 -05:00', '2021-05-26 09:40:00.0000000 -05:00')
,(1, 4, '2021-05-26 09:10:00.0000000 -05:00', '2021-05-26 09:40:00.0000000 -05:00')
,(1, 5, '2021-05-26 09:10:00.0000000 -05:00', '2021-05-26 09:30:00.0000000 -05:00')
,(1, 6, '2021-05-26 09:20:00.0000000 -05:00', '2021-05-26 09:30:00.0000000 -05:00')
,(1, 7, '2021-05-26 09:50:00.0000000 -05:00', '2021-05-26 10:00:00.0000000 -05:00')
,(2, 10, '2021-05-26 08:00:00.0000000 -05:00', '2021-05-26 08:30:00.0000000 -05:00')
,(2, 11, '2021-05-26 08:20:00.0000000 -05:00', '2021-05-26 08:50:00.0000000 -05:00')
SELECT ce.*
,DATEDIFF(minute, ce.ceStartDateTime, ce.ceFinishDateTime) SegmentDuration_Mins
FROM @CalendarEvents ce
-- Compute the total job duration by work center, considering any overlaps, expected result
SELECT *
FROM(VALUES (1, 100), (2, 50)) v(wrcID, TotalDuration_Mins)
-- wrong result
SELECT
ce.wrcID
,SUM(DATEDIFF(minute, ce.ceStartDateTime, ce.ceFinishDateTime)) TotalDuration_Mins
FROM @CalendarEvents ce
GROUP BY
ce.wrcID
This can be represented as follows
the right result is: 120 - 20 = 100 minutes in duration for all scheduled jobs. It's apparent that straight aggregation will not account for overlaps.
If you have any idea(s), even if this is in an approach, please let me know.
Thanks for your time and expertise. I appreciate it.
Vladimir