表a, id, start_date, end_date
表b, id, monthend_date
表a id start_date end_date
1 2021-01-01 2021-12-15
2 2021-01-01 2021-12-15
3 2021-01-01 2021-12-15
表b id monthend_date
1 2021-03-31
2 2021-03-31
2 2021-05-31
备注 这个表的monthend_date 只会出现月末的最后一天日期,来代表这个月都是未出席的
返回
id qujian1 qujian2
1 2021-01-01 2021-02-28
1 2021-04-01 2021-12-15
2 2021-01-01 2021-02-28
2 2021-04-01 2021-04-30
2 2021-06-01 2021-12-15
3 2021-01-01 2021-12-15
用的是什么数据库?
--测试数据
create table test_a_20220218 (id int,start_date datetime,end_date datetime);
insert into test_a_20220218 values (1,'2021-01-01','2021-12-15');
insert into test_a_20220218 values (2,'2021-01-01','2021-12-15');
insert into test_a_20220218 values (3,'2021-01-01','2021-12-15');
create table test_b_20220218(id int,monthend_date datetime);
insert into test_b_20220218 values(1,'2021-03-31');
insert into test_b_20220218 values(2,'2021-03-31');
insert into test_b_20220218 values(2,'2021-05-31');
--查询sql (mysql 8.0 以上,sqlserver去掉RECURSIVE,修改日期计算函数也可以)
with RECURSIVE cte as(
select id,start_date , end_date from test_a_20220218 a
union all
select cte.id,DATE_SUB(cte.start_date,INTERVAL -1 DAY),cte.end_date from cte where DATE_SUB(cte.start_date,INTERVAL -1 DAY)<=cte.end_date
),
t as (
select cte.id,cte.start_date,
date_sub(cte.start_date, interval (rank() over(partition by id order by cte.start_date)) day) gp
from cte where not exists (select 1 from test_b_20220218 b where b.id=cte.id and month(cte.start_date)=month(b.monthend_date))
)
select id,min(start_date),max(start_date) from t group by id,gp