嗨,我需要在startdate
的enddate
和casenumber
之间插入所有日期是SQL(ssms)。因此,casenumber
每天都有一行,而不是每个casenumber
有一行。因此,如果案例开始与结束之间有10天的间隔,它将有10行。如果大小写尚未结束,则原始表中将带有NULL
,但应将其替换为getdate
。请参阅附加图片。
这将获得您的照片:
测试数据设置
create table #test (CaseNumber int, StartDate date, Enddate date)
insert into #test (CaseNumber, StartDate, Enddate)
values(1,'2019-09-18','2019-09-24'),(2,'2019-09-23',NULL)
The代码
;with dt_seq as (
select t.CaseNumber, t.StartDate, isnull(t.Enddate,cast (getdate() as date)) EndDate, t.StartDate [Date]
from #test t
union all
select z.CaseNumber, z.StartDate, z.EndDate, case when z.[Date] < z.EndDate then dateadd(day,1,z.[Date]) else z.EndDate end [Date]
from dt_seq z
where z.[Date] <= dateadd(day,-1,z.EndDate)
)
select c.*, ROW_NUMBER() over (partition by c.CaseNumber order by c.[Date]) [Duration]
from dt_seq c
order by c.CaseNumber, c.[Date]
option ( MaxRecursion 0 )
Reuslts