与@akina差不多,但不那么复杂。此处,cte仅用于识别日期差异大于;1然后加入日期表并联合。开始日期、中间日期和结束日期由一个用于订购的标志标识。
这可以在没有cte的情况下完成,但cte确实有助于澄清(我认为),
注:我对样本数据进行了轻微修改
drop table if exists t;
create table t
(timeoff_id int, timeoff_begin date, timeoff_end date);
insert into t values
( 1 , '2020-10-01' , '2020-10-05'),
( 2 , '2020-11-15' , '2020-11-15'),
( 3 , '2020-12-18' , '2020-12-21');
with cte as
(select 2 as beg,timeoff_id , timeoff_begin, timeoff_end ,datediff(timeoff_end, timeoff_begin) diff
from t
where datediff(timeoff_end, timeoff_begin) > 1)
select cte.beg,cte.timeoff_id,dates.dte
from cte
join dates where dates.dte > cte.timeoff_begin and dates.dte <= date_add(cte.timeoff_begin, interval cte.diff -1 day)
union all
(select 1 as beg,timeoff_id , timeoff_begin dt from t
union all
select 3 ,timeoff_id , timeoff_end from t
)
order by timeoff_id, beg,dte;
+-----+------------+------------+
| beg | timeoff_id | dte |
+-----+------------+------------+
| 1 | 1 | 2020-10-01 |
| 2 | 1 | 2020-10-02 |
| 2 | 1 | 2020-10-03 |
| 2 | 1 | 2020-10-04 |
| 3 | 1 | 2020-10-05 |
| 1 | 2 | 2020-11-15 |
| 3 | 2 | 2020-11-15 |
| 1 | 3 | 2020-12-18 |
| 2 | 3 | 2020-12-19 |
| 2 | 3 | 2020-12-20 |
| 3 | 3 | 2020-12-21 |
+-----+------------+------------+