This returns 22
:
DECLARE @StartDate AS DATE = '20150601'
DECLARE @EndDate AS DATE = '20150630'
SELECT
(DATEDIFF(DAY, @StartDate, @EndDate))
-(DATEDIFF(WEEK, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
Read this article by Jeff Moden for more information.
Explanation:
First, (DATEDIFF(DAY, @StartDate, @EndDate))
will return the difference in number of days. In this case, it'll be 29
. Now, depending on your interpretation of whole days, you may want to add 1 day
to its result.
Next,(DATEDIFF(WEEK, @StartDate, @EndDate) * 2)
:
To quote the article:
DATEDIFF
for the WEEK
datepart doesn't actually calculate weeks, it
calculates the number of times a date range contains dates that
represent pairs of Saturdays and Sundays. To think of it in more
simple terms, it only counts WHOLE WEEKENDS!
So, to exclude the weekends, you must subtract twice the result of this from the first DATEDIFF
. Which now will be: 29 - (2 *4) = 21
.
Finally, this:
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
removes the partial weeks, which only happens when then @StartDate
occurs on a Sunday and the @EndDate
occurs on a Saturday.