在SQL(ssms)中插入开始日期和结束日期之间的日期

问题描述 投票:0回答:1

嗨,我需要在startdateenddatecasenumber之间插入所有日期是SQL(ssms)。因此,casenumber每天都有一行,而不是每个casenumber有一行。因此,如果案例开始与结束之间有10天的间隔,它将有10行。如果大小写尚未结束,则原始表中将带有NULL,但应将其替换为getdate。请参阅附加图片。

image of tables

sql date ssms
1个回答
0
投票

这将获得您的照片:

测试数据设置

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.