日期间隔在一个月的 15 日更改

Date intervals changed on the 15th of a month

我正在寻找一种方法让我的 sql 查询在每个月的 15 日更改我的查询中的日期,以便我的数据拉取具有 "rolling 12 months"。例如,现在,我的查询提取 2018411 和 2019410 之间的日期 (YYYYQMM)。我对其进行了硬编码,因此它看起来像这样:

Select *
From Table
WHERE Spend_Period_YYYYQMM >= 2018411 and Spend_Period_YYYYQMM <= 2019410

我想要一个解决方案,在 12 月 15 日将日期更改为 2018412 和 2019411。

我有一个解决方案可以像下面那样每月更改日期,但希望日期在 15 日更改:

Spend_Period_YYYYQMM between to_char(date(current_date -  cast('13 month' as interval)),'YYYYQMM') 
                         and to_char(date(current_date -  cast('2 month' as interval)),'YYYYQMM')

我该怎么办

我们可以使用一些 CASE clauses and the EOMONTH function 和 GetDate() 来获得你想要的范围。


DECLARE @date DATETIME = GETDATE();
select case 
    when day(@date) <= 14
        then EOMONTH(@date, -13) 
    when day(@date) >= 15
        then EOMONTH(@date, -12)
    end as RollingYearBegin
    ,case 
    when day(@date) <= 14
        then EOMONTH(@date, -2) 
    when day(@date) >= 15
        then EOMONTH(@date, -1)
    end as RollingYearEnd
into #RollingYear

然后,如果您在调用它们时需要以特定方式格式化的值,您可以将上面的温度 table 复杂化一点,或者再做一点 table


    Select cast(concat(datepart(yyyy,RollingYearBegin),  datepart(q,RollingYearBegin), datepart(MM,RollingYearBegin)) as bigint) as YearBegin
,cast(concat(datepart(yyyy,RollingYearEnd),  datepart(q,RollingYearEnd), datepart(MM,RollingYearEnd)) as bigint) as YearEnd
into #YYYYQMM
From #RollingYear

那么,在您的查询中,它将是:

Select *
From Table
WHERE Spend_Period_YYYYQMM BETWEEN (Select YearBegin from #YYYYQMM) AND (Select YearEnd from #YYYYQMM)