I am having difficulties accomplishing a task with MSSQL. I have two tables with periods (begin and end). For example:
Table 1 (ID, begin, end):
A - 01/01/2023 - 31/10/2023
B - 01/01/2023 - 31/03/2023
Table 2 (ID, begin, end):
A - 01/02/2023 - 30/09/2023
B - 01/03/2023 - 30/04/2023
The task is to cut the period in table 2 out of the period in table 1. The expected result for ID A should be:
01/01/2023 - 31/01/2023 and (!) 01/10/2023 - 31/10/2023
and for ID B:
01/01/2023 - 28/02/2023
However, I am having issues with ID A since I should receive two results for one JOIN. Any ideas on how to resolve this?
Union dates: t1.begin, t1.end, t2.begin-1, t2.end+1. From such union create small periods using
lead(). Finally exclude rows with overlapping periods in table2:dbfiddle demo
Edit:
After testing it appears that above query does not handle one day periods required in the output properly. So instead of
unionI usedunion allin the inner query and then additional grouping of result:dbfiddle demo