-1

I am trying to write a query which will work out the difference between two dates but without counting specific days.

select ((DATEPART(weekday,(DATEDIFF(DAY,StartDate,EndDate)))) NOT IN (1,5)) FROM MyTable

In this example I'm trying to remove Monday and Friday from difference days (StartDate EndDate)

Dale K
  • 25,246
  • 15
  • 42
  • 71
  • Perhaps this link? https://stackoverflow.com/questions/7388420/get-datediff-excluding-weekends-using-sql-server – Robin Webb Jul 14 '20 at 09:32
  • 3
    Search for "calendar table". A join to a utility calendar table will allow you to exclude not only weekends, but also other non-business days like holidays. – Dan Guzman Jul 14 '20 at 09:39

1 Answers1

0

Ideally you need calendar table, to do these kinds of calculations easier. Below, I am generating the dates for the range and then counting the days accordingly.

DECLARE @startDate DATE = '2020-07-01'
DECLARE @EndDate DATE = '2020-07-13'

;with AllDates AS
(
    SELECT @StartDate AS DateOf
    UNION ALL
    SELECT DateAdd(day,1,DateOf)
        FROM AllDates
    WHERE DateOf<@EndDate
)
select SUM(CASE WHEN DATENAME(weekday,dateof) in ('Monday','Friday') THEN 0 ELSE 1 END) as SumOfDays
FROM AllDates

+-----------+
| SumOfDays |
+-----------+
|         9 |
+-----------+
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58