I would like to build an SQL query which calculates the difference between 2 dates, without counting the week-end days in the result.
Is there any way to format the
You can try this:
SELECT
Id,
DATEDIFF(d, datefrom, dateto) AS TotDays,
DATEDIFF(wk, datefrom, dateto) AS Wkds,
DATEDIFF(d, datefrom, dateto) - DATEDIFF(wk, datefrom, dateto) AS Days
FROM
YOURTABLE
There is a problem with @lightmania answer I think.
Using values:
select (TO_DATE('06/02/2014', 'DD/MM/YYYY') -
TO_DATE('04/02/2014', 'DD/MM/YYYY') -
2 * (to_char(TO_DATE('06/02/2014', 'DD/MM/YYYY'), 'WW') -
to_char(TO_DATE('04/02/2014', 'DD/MM/YYYY'), 'WW'))) from dual;
Returned 0 instead of 2 that it should have returned.
I have found several of the answers on this thread to not do what they claim. After some experimentation, testing and adjusting, I have this to contribute.
declare @firstdate Date
declare @seconddate Date
set @firstDate = convert(date, '2016-03-07')
set @seconddate = convert(date, '2016-04-04')
select (datediff(dd, @firstDate, @secondDate)) -
(( DateDiff(wk, @firstDate, @secondDate) * 2) -
case when datepart(dw, @FirstDate) = 7 then 1 else 0 end -
case when datepart(dw, @secondDate) = 7 then -1 else 0 end)
Test harness included - you can just adjust the two dates and run your own tests. This assumes that the difference between two adjacent weekday dates is 1. If your country uses different days to signify weekend, then you will have to set the date-base accordingly so your "Saturday" is 7, and your "sunday" is 1.
((sysdate - ced.created_dt) + ((((to_char(ced.created_dt,'IW') - ((to_char(sysdate,'YY') - to_char(ced.created_dt,'YY'))* 52))
- to_char(to_char(sysdate,'IW')))) * 2)) duration_in_weekdays