SQL to calculate week days per date period

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)

For MySQL you would need to:
Change FLOOR to TRUNCATE
Change CASE WHEN ... END to IF
Change DATEPART(dw, to TRUNCATE(

Tags

Comments