首页 > 解决方案 > 根据间隔(月/季)查找下一个日期

问题描述

CREATE TABLE @Temp(
    Date datetime,
    Flag bit)

@Temp table as data from 01-04-2019  to  31-04-2020  (366 records) and flag=0

DECLARE startdate date='12-04-2019', interval  int  =1 OR 3

预期结果:如果间隔为 1 个月,则基于开始日期,标记将在记录下方更新为 1,其余为 0

    date         flag
    01-04-2019    0
    .             0
    .             0
    12-05-2019    1
    .             0
    .             0  
    12-06-2019    1
    .             0
    .             0
    12-07-2019    1
    ..            0
    31-04-2020    0

如果间隔为 3 个月,则标志将更新为 1 季度

      date        flag
    01-04-2019    0
    .             0
    .             0
    12-07-2019    1
    .             0
    .             0  
    12-10-2019    1
    .             0
    .             0
    12-01-2020    1
    .             0
    31-04-2020    0

我被困在试图得到结果。我正在使用 SQL Server 2017。

标签: sqlsql-server

解决方案


我花了一段时间才意识到你的日期与我习惯的格式不同。

我会使用公用表表达式而不是游标。除此之外,请考虑任何给定日期和开始日期之间的月差。取该差异的模数(这就是“%”符号的含义)。如果它是 0,那么你的间隔已经被击中,所以激活你的标志。

declare 
    @startdate date = '04.01.2019',
    @interval int = 3; -- or 1, or whatever

with

    dates as (

        select      @startdate dt, 1 flag

        union all
        select      ap.nextDt, 

                    flag = 
                        case
                        when day(ap.nextDt) <> day(@startdate) then 0 
                        when (month(ap.nextDt) - month(@startdate)) % @interval = 0 then 1
                        else 0 
                        end

        from        dates
        cross apply (select nextDt = dateadd(day,1,dt)) ap
        where       dt <= dateadd(year,1,@startdate)

    )

    select    *           
    from      dates 
    option    (maxrecursion 367)

推荐阅读