我正在使用一种算法,该算法需要根据工作日数进行计算。
样本数据
CREATE TABLE Holidays
(
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO Holidays VALUES ('2019-07-16', '2019-07-17')
DECLARE @CurrentWeekDay INT
SET DATEFIRST 1
// Returns day of the week as int, ex... Monday = 0, Tue = 1....
SET @CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1
此操作从星期一开始,直到星期五0、1、2、3、4,再减去一周的总天数
现在我创建了2个新变量
DECLARE @TotalHolidays INT, @IsSameWeek BIT
// If there is a holiday in the current week get the holiday date, else just cast 0
SET @IsSameWeek =
CASE
WHEN (SELECT DATEDIFF(WEEK,GETDATE(), (SELECT TOP 1 EndDate FROM Holidays))) = -1 THEN 0
ELSE
1
END
SET @TotalHolidays =
CASE
WHEN @IsSameWeek = 1 THEN (SELECT DATEDIFF(day, StartDate, EndDate ) FROM Holidays)
ELSE
0
END
因此,基本上使用该简单公式即可计算出一周中剩余的天数
DECLARE @TotalDays = 5,
SET @TotalDays = @TotalDays - @TotalHolidays - @CurrentWeekDay
这一切都很好,但这仅在假期在周末结束时有效。
Datefirst
M T W T F
0 1 2 3 4
如果星期四和星期五是假期,则该算法效果很好,但是如果星期三是假期,那么它将破坏所有内容
基本上我需要它,所以如果星期三是假期
Datefirst就像
M T W T F
0 1 2 3
全部设置完毕,这就是整个代码
CREATE TABLE Holidays
(
StartDate DATETIME,
EndDate DATETIME
)
INSERT INTO Holidays VALUES ('2019-07-18', '2019-07-19')
DECLARE @TotalHolidays INT, @IsSameWeek BIT, @CurrentWeekDay INT
SET DATEFIRST 1
SET @CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1
SET @IsSameWeek =
CASE
WHEN (SELECT DATEDIFF(WEEK,GETDATE(), (SELECT TOP 1 EndDate FROM Holidays))) = -1 THEN 0
ELSE
1
END
SET @TotalHolidays =
CASE
WHEN @IsSameWeek = 1 THEN (SELECT DATEDIFF(day, StartDate, EndDate ) FROM Holidays)
ELSE
0
END
DECLARE @DaysLeft INT
SET @DaysLeft = 5 - @TotalHolidays - @CurrentWeekDay
这将在返回2时返回0