在营业日表中跳过假期

时间:2017-04-25 01:22:43

标签: sql sql-server date sql-scripts

我使用以下脚本来确定特定月份的工作日

DECLARE @startdate DATETIME
SET @startdate ='20170401'
;
WITH bd AS(
SELECT
DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, @startdate), 0)
) AS bd, 1 AS n
UNION ALL
SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, bd.bd) + @@DATEFIRST - 1) % 7
    WHEN 5 THEN 3
    WHEN 6 THEN 2
    ELSE 1
END,
bd.bd
) AS db,
bd.n+1
FROM bd WHERE MONTH(bd.bd) = MONTH(@startdate)
)
SELECT * INTO #BD
FROM (
SELECT 'BD'+ CAST(n AS VARCHAR(5)) AS Expected_Date_Rule, bd AS Expected_Calendar_Date
from bd
) AS x

这个表的结果很好。 Bd是特定月份的日历日,n是工作日编号,脚本的工作是不将周末计为工作日。

bd                      n
----------------------- -----------
2017-04-03 00:00:00.000 1
2017-04-04 00:00:00.000 2
2017-04-05 00:00:00.000 3
2017-04-06 00:00:00.000 4
2017-04-07 00:00:00.000 5
2017-04-10 00:00:00.000 6
2017-04-11 00:00:00.000 7
2017-04-12 00:00:00.000 8
2017-04-13 00:00:00.000 9
2017-04-14 00:00:00.000 10
2017-04-17 00:00:00.000 11
2017-04-18 00:00:00.000 12
2017-04-19 00:00:00.000 13
2017-04-20 00:00:00.000 14
2017-04-21 00:00:00.000 15
2017-04-24 00:00:00.000 16
2017-04-25 00:00:00.000 17
2017-04-26 00:00:00.000 18
2017-04-27 00:00:00.000 19
2017-04-28 00:00:00.000 20
2017-05-01 00:00:00.000 21

但是我注意到潜在的问题将在7月发生,其中输出将计算在7月4日作为BD2,它应该算作BD3。有些人创建了一个假期表,并在所有假期中更新(原因是拼写错误)。

Holiday table

1              2017-01-01          New Year Day
4              2017-01-02          New Year Day-Follow
1              2017-01-16          MArtin Luther King Day
4              2017-01-17          MArtin Luther King Day-Follow
1              2017-02-20          Preseiednt Day
4              2017-02-21          Preseiednt Day-Follow
1              2017-05-29          Memorial Day
4              2017-05-30          Memorial Day-Follow
1              2017-07-04          Independence Day
4              2017-07-05          Independence Day-Follow
1              2017-09-04          Labour Day
4              2017-09-05          Labour Day-Follow
1              2017-10-09          Columbus Day
4              2017-10-10          Columbus Day-Follow
1              2017-11-10          Vetrans Day
4              2017-11-11          Vetrans Day-Follow
1              2017-11-23          ThanksGiving
1              2017-11-24          Day After Thanks Giving
4              2017-11-24          ThanksGiving-Follow
4              2017-11-25          Day After Thanks Giving-Follow
1              2017-12-25          Christmas
4              2017-12-26          Christmas-Follow

我在想,可能有某种方式我可以更新我的脚本来检查假期表并跳过假期而不计算它作为工作日。有什么提示吗?

0 个答案:

没有答案