我使用以下脚本滚动12个月。如何修改它以获得当前年份和前年份?
declare @start date = convert(date,dateadd(M,-12,getdate()))
declare @end date = getdate()
;with months (date)
AS
(
select @start
union all
select dateadd(month,1,date)
from months
where dateadd(month,1,date) < =@end
)
,
-----------------------------------------------------
--List of periods (12 months from today)
-----------------------------------------------------
list_param as (
select
left(convert(varchar, Date,112),6) as [Period]
from months)
-----------------------------------------------------
--Calculation parameters
-----------------------------------------------------
select
Period,
Period AS Inv_M,
left(convert(varchar, dateadd(M,-1,convert(date,Period+'01')),112),6) AS Inv_M_1,
case when Period=left(convert(varchar, getdate(),112),6) then convert(date, getdate())
else dateadd(M,1,convert(date,Period+'01'))
end as Backlog_M,
case when Period=left(convert(varchar, getdate(),112),6) then convert(date,dateadd(day,-day(getdate()-1),getdate())) else convert(date,Period+'01') end as Backlog_M_1,
left(Period,4) as Inv_YTD,
left(Period,4)+'01' as Start_Inv_YTD
from list_param
order by Period;
结果,我得到以下结果:
> Period Inv_M Inv_M_1 Backlog_M Backlog_M_1 Inv_YTD Start_Inv_YTD
> 201802 201802 201801 2018-03-01 2018-02-01 2018 201801
> 201803 201803 201802 2018-04-01 2018-03-01 2018 201801
> 201804 201804 201803 2018-05-01 2018-04-01 2018 201801
> 201805 201805 201804 2018-06-01 2018-05-01 2018 201801
> 201806 201806 201805 2018-07-01 2018-06-01 2018 201801
> 201807 201807 201806 2018-08-01 2018-07-01 2018 201801
> 201808 201808 201807 2018-09-01 2018-08-01 2018 201801
> 201809 201809 201808 2018-10-01 2018-09-01 2018 201801
> 201810 201810 201809 2018-11-01 2018-10-01 2018 201801
> 201811 201811 201810 2018-12-01 2018-11-01 2018 201801
> 201812 201812 201811 2019-01-01 2018-12-01 2018 201801
> 201901 201901 201812 2019-02-01 2019-01-01 2019 201901
> 201902 201902 201901 2019-02-11 2019-02-01 2019 201901
答案 0 :(得分:0)
您只需要更改@StartDate的填充方式即可。将其切换为类似的格式即可获取上一年的开始日期。
dateadd(year, datediff(year, 0, getdate()) - 1, 0)