简单讲,需要用MY SQL,将跨月的数据,按照月份进行拆分,求指教如何实现……
原始数据:
begindate,enddate,org,type
20220101,20220215,A,22
20220216,29991231,A,33
期望拆分后实现:
begindate,enddate,org,type
20220101,20220131,A,22
20220201,20220215,A,22
20220216,29991231,A,33
为什么要拆分开,对于后续分析又不会有什么帮助,本来拉链的形式就是为了减少快照的冗余,结果你要给弄个时间的冗余~~
这种题已经有不少人问过了,如果是mysql8.0以上,支持递归sql。
但是你这题有一点点不一样,就是最后一个月份竟然不要拆?那我只能假定先用where enddate<>'29991231'剔除掉这部分数据先处理了,再union all回这一部分数据了。
然后你这数据有点少,我多造了一点数据
--测试数据
drop table test_a_20220308;
create table test_a_20220308 (id int,start_date date,end_date date,org VARCHAR(10),type VARCHAR(10));
insert into test_a_20220308 values (1,'2021-01-01','2021-03-15','A','22');
insert into test_a_20220308 values (2,'2021-03-16','2021-12-15','A','22');
insert into test_a_20220308 values (3,'2021-04-05','2021-07-08','A','33');
--查询sql (mysql 8.0 以上)
with RECURSIVE cte as(
select
id,
start_date ,
last_day( start_date) end_date1 ,
end_date,
org,
type
from test_a_20220308 a
union all
select
cte.id,
date_add(start_date-day(start_date)+1,interval 1 month),
least(last_day(date_sub(start_date,interval -1 month)),end_date),
end_date,
org,
type
from cte where date_add(start_date-day(start_date)+1,interval 1 month)<=cte.end_date
)
select id,start_date,end_date1 end_date,org,type from cte order by id ,start_date