SQL Server:每月的第一个工作日

时间:2018-09-17 20:05:39

标签: sql-server

如何将假期表合并到下面的SQL中?结果返回第一个工作日,但由于18年1月1日是星期一假期,我需要工作日2。

DECLARE @DATE DATETIME;
SET @DATE = '1/1/2018';

SELECT 
    CASE
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Saturday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 2
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Sunday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 2
       WHEN DATENAME(WEEKDAY, DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)) = 'Monday'
          THEN DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0) + 1
       ELSE DATEADD(mm, DATEDIFF(MM, 0, @DATE), 0)
   END;

1 个答案:

答案 0 :(得分:0)

我认为这将对您有所帮助,您可以像您提到的那样检查此sqlscript,我给了3个不同的日期来检查正确的答案:

Declare @date date = '01/01/2018' --getdate()

SELECT CASE 
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

set @date = '04/01/2018' --getdate()

SELECT CASE 
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

set @date = '09/01/2018' --getdate()

SELECT CASE 
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Saturday'
            THEN dateadd(mm, DATEDIFF(MM, 0, getdate()), 0) + 2
        WHEN DATENAME(WEEKDAY, dateadd(mm, DATEDIFF(MM, 0, @date), 0)) = 'Sunday'
            THEN dateadd(mm, DATEDIFF(MM, 0, @date), 0) + 1
        ELSE dateadd(mm, DATEDIFF(MM, 0, @date), 0)
        END

请参考:-First business day of the current month - SQL Server