Count work days between two dates

前端 未结 24 2709
失恋的感觉
失恋的感觉 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:52

    One approach is to 'walk the dates' from start to finish in conjunction with a case expression which checks if the day is not a Saturday or a Sunday and flagging it(1 for weekday, 0 for weekend). And in the end just sum flags(it would be equal to the count of 1-flags as the other flag is 0) to give you the number of weekdays.

    You can use a GetNums(startNumber,endNumber) type of utility function which generates a series of numbers for 'looping' from start date to end date. Refer http://tsql.solidq.com/SourceCodes/GetNums.txt for an implementation. The logic can also be extended to cater for holidays(say if you have a holidays table)

    declare @date1 as datetime = '19900101'
    declare @date2 as datetime = '19900120'
    
    select  sum(case when DATENAME(DW,currentDate) not in ('Saturday', 'Sunday') then 1 else 0 end) as noOfWorkDays
    from dbo.GetNums(0,DATEDIFF(day,@date1, @date2)-1) as Num
    cross apply (select DATEADD(day,n,@date1)) as Dates(currentDate)
    

提交回复
热议问题