我正在尝试创建一个脚本,该脚本将根据开始周和结束周的参考日期为我提供财务周
例如,假设我有带有StartWeek和EndWeek的表列,例如:
StartWeek | EndWeek
----------|---------
20190603 | 20190609
20190610 | 20190616
20190617 | 20190623
20190624 | 20190630
20190701 | 20190707
...
我希望脚本生成以下内容:
FiscalDateStart | FiscalDateEnd | NumOfDays | WeekDayStart | WeekDayEnd
----------------|----------------|------------|--------------|-----------
2019-06-05 | 2019-06-09 | 5 | Wednesday | Sunday
2019-06-10 | 2019-06-16 | 7 | Monday | Sunday
2019-06-17 | 2019-06-23 | 7 | Monday | Sunday
2019-06-24 | 2019-06-30 | 7 | Monday | Sunday
2019-07-01 | 2019-07-02 | 2 | Monday | Tuesday
我在堆栈上发现了以下逻辑:
DECLARE @StartDate DATE = '2019-06-05'
, @EndDate DATE = '2019-07-02'
SET DATEFIRST 1
SET LANGUAGE French;
SET NOCOUNT ON;
select *
from
(Select
WeekNum = Dense_Rank() over (Partition By FY,FM Order By FW)
,StartDate = Min(D) over (Partition By FY,FM,FW )
,EndDate = Max(D) over (Partition By FY,FM,FW )
,NumOfDays = DATEDIFF(DAY, Min(D) over (Partition By FY,FM,FW ), Max(D) over (Partition By FY,FM,FW )) + 1
From
(
/* Establish calendar rules/functions for Fiscal Year (FY), Fiscal Month (FM), Fiscal Week (FW), & Fiscal Day (D) */
Select FY = DatePart(Year,@StartDate)-1+sum(case when convert(varchar(5),@StartDate,101)=convert(varchar(5),D,101) then 1 else 0 end) over (Order By D)
,FM = sum(case when DatePart(Day,D)=DatePart(Day,@StartDate) then 1 else 0 end) over (Order By D)
,FW = sum(case when DatePart(WeekDay,D)=1 then 1 else 0 end) over (Order By D)
,D
From (
/* Generate Fiscal Day (D) rule based on @StartDate & @EndDate */
Select Top (DateDiff(DAY,@StartDate,@EndDate)+1)
D = DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),@StartDate)
From master..spt_values n1,master..spt_values n2
) A1
) A
--Order By D
) a
group by
WeekNum, StartDate, EndDate, NumOfDays
问题在于,我们强制上述查询中的@StartDate为2019-06-05。但是,我需要上面的脚本来生成相同的结果,但是基于截至2019-06-03的@StartDate。
任何帮助将不胜感激。