没有复杂的算法。带有交叉连接、介于和最大/最小函数的简单 sql 即可。
create table abc
( id integer,
attr1 varchar(3),
start_date date,
end_date date)
PRIMARY INDEX(ID);
create table PQR
( id integer,
attr2 varchar(3),
start_date date,
end_date date)
PRIMARY INDEX(ID);
INSERT INTO abc VALUES(1,'LMN','2017-01-01','2017-02-28');
INSERT INTO abc VALUES(1,'HGI','2017-02-28','2017-03-15');
INSERT INTO abc VALUES(1,'STI','2017-03-15','2099-12-31');
INSERT INTO PQR VALUES(1,'KLM','2017-01-01','2017-01-20');
INSERT INTO PQR VALUES(1,'TLF','2017-01-20','2017-04-04');
INSERT INTO PQR VALUES(1,'SNQ','2017-04-04','2099-12-31');
select a.id,a.attr1,p.attr2,
cast(greatest(cast(a.start_date as int),cast(p.start_date as int)) as date)start_date,
cast(least(cast(a.end_date as int),cast(p.end_date as int)) as date)end_date
from abc a
inner join pqr p
on a.id=p.id
where a.start_date between p.start_date and p.end_date
or a.end_date between p.start_date and p.end_date
order by 4;
输出:
id attr1 attr2 start_date end_date
1 1 LMN KLM 1/1/2017 1/20/2017
2 1 LMN TLF 1/20/2017 2/28/2017
3 1 HGI TLF 2/28/2017 3/15/2017
4 1 STI TLF 3/15/2017 4/4/2017
5 1 STI SNQ 4/4/2017 12/31/2099
唯一的区别是我用 2099 而不是 1999 来简化事情。您也可以使用 1999 并自定义此查询(虽然不是首选)。