sql

By steve, 10 June, 2016

The following SQL will calculate the number of workdays in a given month:

WITH t as 
	(
	select 1 x
	union all 
	select x + 1
	from t
	where x < day(dateadd(day, -1, dateadd(month, 1, datefromparts([year], [month], 1))))
	)
SELECT COUNT(x) NumWeekDays from t 
whereDATEPART(dw, datefromparts([year], [month], x)) not in (1,7)

And for Connectwise, the following would calculate the number of work days in a given month:

Tags

By steve, 15 April, 2014

The first part approximates the number of whole weeks with a margin of error of maybe adding an extra week
The second part adjusts for the remaining days, and corrects the first part if it adds an extra week.

SELECT (FLOOR((datediff(day, @Start, @End) - DATEPART(dw, @End) + DATEPART(dw, @Start)) / 7) * 5) + (DATEPART(dw, @End) - DATEPART(dw, @Start) + 1 + CASE WHEN DATEPART(dw, @Start) = 1 THEN -1 ELSE 0 END + CASE WHEN DATEPART(dw, @End) = 7 THEN -1 ELSE 0 END)

Tags