add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table #Table1 (ID varchar(1), d1 date, d2 date);
insert into #table1 values ('A', '2019-01-01', '2019-12-31')
insert into #table1 values ('B', '2019-09-05', '2019-12-31');

create table #Table2(ID varchar(1), d1 date, d2 date);
insert into #table2 values ('A', '2019-01-02', '2019-01-02')
insert into #table2 values
('B', '2019-01-01', '2019-06-30'),
('B', '2019-07-02', '2019-09-04');
5 rows affected
select id, min(d1) d1, max(d2) d2
from (
select id, d1, d2, sum(mrk) over (partition by id order by d1, d2) grp
from (
select t.id, t.d1, t.d2,
case when lag(t.d2) over (partition by t.id order by t.d1, t.d2) = t.d1
then 0 else 1 end mrk
from (
select id, dt d1, lead(dt) over (partition by id order by dt) d2
from (
select id, d1 dt from #table1 union all select id, d2 from #table1 union all
select id, dateadd(day, -1, d1) d1 from #table2 union all
select id, dateadd(day, 1, d2) d2 from #table2) u ) t
left join #table2 a on a.id = t.id and a.d1 < t.d2 and t.d1 < a.d2
where a.id is null and t.d2 is not null) t) x
group by id, grp order by id, d1, d2
id d1 d2
A 2019-01-01 2019-01-01
A 2019-01-03 2019-12-31
B 2019-07-01 2019-07-01
B 2019-09-05 2019-12-31