我正在寻找一种方法,让我的sql查询在每个月的15号更改查询中的日期,以便我的数据提取具有“连续12个月”的状态。例如,现在,我的查询提取了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')
我应该怎么做
答案 0 :(得分:0)
我们可以使用一些CASE clauses和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
然后,如果在调用它们时需要以特定方式格式化的值,则可以使该临时表复杂一些,或者仅制作另一个小表
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)