這個的最右邊一列將計算任何日期在1月份的上一個星期日。我已經將其他欄目作爲一種簡單的方式來記錄和實驗邏輯。
沒有分支邏輯,它都是純日期數學,所以它應該合理快速地進行聚合,並且應該能夠在日期列上使用索引。
DECLARE @Date DATE = '20170205';
SELECT SampleDate= @Date ,
EndOfSampleMonth = EOMONTH(@Date) ,
SampleMonthNumber = DATEPART(MONTH,@Date) ,
MostRecentJanuaryForSampleMonth = DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date) ,
LastDayOfMostRecentJanuary = EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)) ,
WeekDayOfLastDayOfMostRecentJanuary = DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date))) ,
LastSundayOfJanuary = DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date))) ,
LastSundayOfJanuaryDayOfYear= DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))) ,
PushSampleDateToFiscalYear = DATEADD(DAY,(DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date))))) * -1 ,@date) ,
PreviousLastSundayInJanuaryForSampleDate = DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH
,DATEADD(DAY,((DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))))-1) * -1 ,@Date))-1)*-1
,DATEADD(DAY,((DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))))-1) * -1 ,@Date))))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH
,DATEADD(DAY,((DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))))-1) * -1 ,@Date))-1)*-1
,DATEADD(DAY,((DATEPART(DAYOFYEAR,DATEADD(DAY,(DATEPART(WEEKDAY,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))-1)*-1,EOMONTH(DATEADD(MONTH,(DATEPART(MONTH,@Date)-1)*-1,@Date)))))-1) * -1 ,@Date))))
如果你被一個財政年度試圖組,在今年()函數來輸出包PushSampleDatetoFiscalYear本財年的日期所屬。要將其用於表格,請將@Date替換爲您自己的日期字段。
更新與樣品結果:
SampleDate PreviousLastSundayInJanuaryForSampleDate
2008-06-03 2008-01-27
2008-12-20 2008-01-27
2009-07-08 2009-01-25
2010-01-24 2009-01-25
2010-08-12 2010-01-31
2011-02-28 2011-01-30
2011-09-16 2011-01-30
2012-04-03 2012-01-29
2012-10-20 2012-01-29
2013-05-08 2013-01-27
2013-11-24 2013-01-27
2014-06-12 2014-01-26
2014-12-29 2014-01-26
2015-07-17 2015-01-25
2016-02-02 2016-01-31
2016-08-20 2016-01-31
2017-03-08 2017-01-29
2017-09-24 2017-01-29
2018-04-12 2018-01-28
2018-10-29 2018-01-28
2019-05-17 2019-01-27
2019-12-03 2019-01-27
2020-06-20 2020-01-26
所需的輸出是最後一個星期日月份一個月,而不是當前日期的最後一個星期日。 –
@ b-balamanigandan對不起,無法正常工作 – user2331670