需要一个辅助表:
-----------------------------------------------------------------------------------------------------------
declare @t1 table(单元编号 varchar(10),开始日期 datetime,结束日期 datetime)
insert into @t1 select '001','2005-1-1','2005-4-1'declare @t2 table(id int)
insert into @t2
select 1 union select 2 union select 3 union
select 4 union select 5 union select 6
-- ...select
a.单元编号,
开始日期=case b.id
when 1
then a.开始日期
else cast((convert(char(8),dateadd(mm,(b.id-1),a.开始日期),120)+'02') as datetime)
end,
结束日期=case
when b.id<datediff(mi,a.开始日期,a.结束日期)
then cast((convert(char(8),dateadd(mm,b.id,a.开始日期),120)+'01') as datetime)
else
a.结束日期
end
from
@t1 a,
@t2 b
where
(b.id+(case day(a.结束日期) when 1 then 0 else 1 end))<=datediff(mm,a.开始日期,a.结束日期)/*
单元编号 开始日期 结束日期
-----------------------------------------
001 2005-1-1 2005-2-1
001 2005-2-2 2005-3-1
001 2005-3-2 2005-4-1
*/
-----------------------------------------------------------------------------------------------------------
declare @t1 table(单元编号 varchar(10),开始日期 datetime,结束日期 datetime)
insert into @t1 select '001','2005-1-1','2005-4-1'declare @t2 table(id int)
insert into @t2
select 1 union select 2 union select 3 union
select 4 union select 5 union select 6
-- ...select
a.单元编号,
开始日期=case b.id
when 1
then a.开始日期
else cast((convert(char(8),dateadd(mm,(b.id-1),a.开始日期),120)+'02') as datetime)
end,
结束日期=case
when b.id<datediff(mi,a.开始日期,a.结束日期)
then cast((convert(char(8),dateadd(mm,b.id,a.开始日期),120)+'01') as datetime)
else
a.结束日期
end
from
@t1 a,
@t2 b
where
(b.id+(case day(a.结束日期) when 1 then 0 else 1 end))<=datediff(mm,a.开始日期,a.结束日期)/*
单元编号 开始日期 结束日期
-----------------------------------------
001 2005-1-1 2005-2-1
001 2005-2-2 2005-3-1
001 2005-3-2 2005-4-1
*/
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货