简体   繁体   English

根据间隔(月/季)查找下一个日期

[英]Find the next date based on Interval (month/quaterly)

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

Expected Result: If interval is 1 month, based on startdate, flag to be updated as 1 below records and rest for 0预期结果:如果间隔为 1 个月,则基于 startdate,标记将在记录下方更新为 1,rest 为 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

If interval is 3 month, flag to be updated as 1 for quarter如果间隔为 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

I am stuck trying get the result.我被困在试图得到结果。 I am using SQL Server 2017.我正在使用 SQL 服务器 2017。

Took me awhile to realize that your dates were in different format than I'm used to.我花了一段时间才意识到你的日期与我习惯的格式不同。

I would go with a common table expression as opposed to a cursor.我会使用公共表表达式 go 而不是 cursor。 Besides that, consider the month difference between any given date and the start date.除此之外,请考虑任何给定日期和开始日期之间的月差。 Take the modulo of that difference (that's what the '%' symbol is).取该差异的模数(这就是“%”符号的含义)。 If it's 0, then your interval has been hit and so activate your flag.如果它是 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM