选择下个月的第一个工作日

时间:2018-10-30 22:54:53

标签: sql sql-server

我正在尝试修改在这里找到的其他人的代码,以查找下个月的第一个工作日(Link)

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

这是我想出的(不起作用):

select CASE 
                WHEN DATENAME(WEEKDAY, eomonth(dateadd(mm, DATEDIFF(MM, 0, getdate()),1), 0 )) = 'Saturday'
                    THEN eomonth(dateadd(mm, DATEDIFF(MM, 0, getdate()), 0),1) + 2
                WHEN DATENAME(WEEKDAY, eomonth(dateadd(mm, DATEDIFF(MM, 0, getdate()),1), 0)) = 'Sunday'
                    THEN eomonth(dateadd(mm, DATEDIFF(MM, 0, getdate()), 0),1) + 1
                ELSE eomonth(dateadd(mm, DATEDIFF(MM, 0, getdate()), 1),1)
                end

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您的查询实现类似于SQL Server。您可以使用DATEFROMPARTSEOMONTH函数来获取下个月的第一天,然后使用CASE表达式中的DATENAME来确定第一天,如下所示(仅适用于SQL Server)。

-- get first day of next month using DATEFROMPARTS
Declare @NextMonthFirstDate datetime = DATEFROMPARTS(YEAR(GETDATE()),MONTH(GETDATE())+1,1)

-- then use CASE expression 
Select CASE WHEN DATENAME(WEEKDAY, @NextMonthFirstDate) = 'Sunday'
                THEN @NextMonthFirstDate + 1
            WHEN DATENAME(WEEKDAY, @NextMonthFirstDate) = 'Saturday'
                THEN @NextMonthFirstDate + 2
            ELSE @NextMonthFirstDate END as FirstWeekDayOfnextMonth