Wednesday, October 20, 2010

Get the total working days between two dates(Excluding the Sundays and Saturdays)

Question:
I would like to get the total working days between two dates.
Answer:
You can first calculate the total days and non-working days with DATEDIFF function. Then use subtraction to get working days.

The SQL clause is shown below.

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2009/12/01'
SET @EndDate = '2009/12/31'

SELECT ((DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @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))

No comments:

Post a Comment