We are using SQL Server.
In our CASE WHEN statement, I need to check if the number of days between the 2 dates are > 3 business days (so excluding weekends and holidays).
CASE WHEN end_date - start_date > 3 THEN 0 --> this need to exclude
weekend and holidays
WHEN CODE = 1 THEN 1
WHEN CODE =2 THEN 2
ELSE 3
END AS MyColumn
Say I have a holiday calendar table that has column HolidayDates that contains all the holidays, for ex: 12/25/2018, 12/31/2018, etc.
HolidayDates 12/25/2018 12/31/2018 So, if
Date1 = 1/2/19 (Wednesday)
Date2 = 12/27/18 (Thursday)
The number of business days in between Date1 and Date2 is 3 days (12/27, 12/28 and 12/31).
The above query will get the number of business days including weekends and holidays.
How do I also exclude weekends and holidays in the query ?
Thank you.
Edited with answer:
select start_date, end_date,
datediff(day, mt.start_date, mt.end_date) datediff,
(select
(datediff(wk, mt.start_date, mt.end_date) )
+(case when datename(dw, mt.start_date) = 'sunday' then 1 else 0 end)
+(case when datename(dw, mt.end_date) = 'saturday' then 1 else 0 end)
) weekend,
(select count(*) from HolidayDates hd
where hd.holydayDate between mt.start_date and mt.end_date
) as [holydays (not weekends)],
datediff(day, mt.start_date, mt.end_date)
-(select
(datediff(wk, mt.start_date, mt.end_date) )
+(case when datename(dw, mt.start_date) = 'sunday' then 1 else 0 end)
+(case when datename(dw, mt.end_date) = 'saturday' then 1 else 0 end)
) * 2
-(select count(*) from HolidayDates hd
where hd.holydayDate between mt.start_date and mt.end_date
)
as diff
from MyTable mt