Count work days between two dates

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

    I know this is an old question but I needed a formula for workdays excluding the start date since I have several items and need the days to accumulate correctly.

    None of the non-iterative answers worked for me.

    I used a defintion like

    Number of times midnight to monday, tuesday, wednesday, thursday and friday is passed

    (others might count midnight to saturday instead of monday)

    I ended up with this formula

    SELECT DATEDIFF(day, @StartDate, @EndDate) /* all midnights passed */
         - DATEDIFF(week, @StartDate, @EndDate) /* remove sunday midnights */
         - DATEDIFF(week, DATEADD(day, 1, @StartDate), DATEADD(day, 1, @EndDate)) /* remove saturday midnights */
    

提交回复
热议问题