J C
asked on
How to factor in working days (MS SQL 2008)
DATEDIFF(dd, LotStartDate, aend_fndpr) AS daysFromStartAend_fndpr
What can I do to factor in working days to this equation? Is it possible?
Thanks!
a quick method for calculation of working days simply excludes weekends - it isn't as accurate as using a table of dates as proposed by acperkins - nonetheless you may find it useful.
SELECT
ID
, (DATEDIFF(dd, LotStartDate, aend_fndpr) + 1)
-(DATEDIFF(wk, LotStartDate, aend_fndpr) * 2)
-(CASE WHEN DATENAME(dw, LotStartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, aend_fndpr) = 'Saturday' THEN 1 ELSE 0 END)
as working_days
, <<other fields >>
from your_table
basically it's (the full numbers of days) - (the no. of weekends * 2 between start and end) - 1 (if starting on Sunday) - 1 (if ending on Saturday). See it in operation, at sqlfiddle, here http://sqlfiddle.com/#!3/0cb83/1
SELECT
ID
, (DATEDIFF(dd, LotStartDate, aend_fndpr) + 1)
-(DATEDIFF(wk, LotStartDate, aend_fndpr) * 2)
-(CASE WHEN DATENAME(dw, LotStartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, aend_fndpr) = 'Saturday' THEN 1 ELSE 0 END)
as working_days
, <<other fields >>
from your_table
basically it's (the full numbers of days) - (the no. of weekends * 2 between start and end) - 1 (if starting on Sunday) - 1 (if ending on Saturday). See it in operation, at sqlfiddle, here http://sqlfiddle.com/#!3/0cb83/1
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@PortletPaul - Great comparison. The method I posted does assume that the input days are weekdays.
From a logic perspective maybe querying a date dimention table is the simplest:
From a logic perspective maybe querying a date dimention table is the simplest:
WITH CTE AS (
SELECT 0 as number, cast(cast(getdate() as date)as datetime) as dt
UNION ALL
SELECT number+1, dt+1
FROM CTE
WHERE number < 366
)
select count(*) from cte
where datepart(dw,dt) between 2 and 6
and dt between getdate() and getdate()+7*3--three weeks
option (maxrecursion 1000)
Absolutely. Build yourself a WorkDays table that contains all the workdays from here to say 2030 and then your query becomes trivial. Let me know if you are interested.