Count work days between two dates

前端 未结 24 2708
失恋的感觉
失恋的感觉 2020-11-22 01:05

How can I calculate the number of work days between two dates in SQL Server?

Monday to Friday and it must be T-SQL.

24条回答
  •  遇见更好的自我
    2020-11-22 01:51

    Using a date table:

        DECLARE 
            @StartDate date = '2014-01-01',
            @EndDate date = '2014-01-31'; 
        SELECT 
            COUNT(*) As NumberOfWeekDays
        FROM dbo.Calendar
        WHERE CalendarDate BETWEEN @StartDate AND @EndDate
          AND IsWorkDay = 1;
    

    If you don't have that, you can use a numbers table:

        DECLARE 
        @StartDate datetime = '2014-01-01',
        @EndDate datetime = '2014-01-31'; 
        SELECT 
        SUM(CASE WHEN DATEPART(dw, DATEADD(dd, Number-1, @StartDate)) BETWEEN 2 AND 6 THEN 1 ELSE 0 END) As NumberOfWeekDays
        FROM dbo.Numbers
        WHERE Number <= DATEDIFF(dd, @StartDate, @EndDate) + 1 -- Number table starts at 1, we want a 0 base
    

    They should both be fast and it takes out the ambiguity/complexity. The first option is the best but if you don't have a calendar table you can allways create a numbers table with a CTE.

提交回复
热议问题