I have first table with defined work times: FreeTimes table (start datetime, end datetime) and second table with already planned tasks: TaskTime table (start datetime, end datetime).
I need somehow to subtract second table from first, so i get a result set of remainig FreeTimes under this conditions:
- in case where TaskTime (or more TaskTimes) is in middle of FreeTime, i need to split FreeTime to time before task and time ramaining after task
- in case when TaskTime is overlapping entire FreeTime i need to filter out this FreeTime
- in case where TaskTime is intersecting with FreeTime i need to subtract TaskTime from FreeTime and leave only remaing part of FreeTime
The general way I’d solve this is as follows:
Where we basically order all datetime values of interest, and then for each pair of successive values, work out if there’s some overlap with the
TaskTimestable. If there is, then that pair shouldn’t be in the final result. (edit – we also have to check that the interval pair does actually overlap withFreeTimestoo)You can, if needed, take this further and merge intervals (if there are overlapping rows in
FreeTimes, you may end up with multiple intervals which are adjacent to each other)