Calculate difference between 2 dates in SQL, excluding weekend days

前端 未结 10 983
礼貌的吻别
礼貌的吻别 2020-12-04 01:34

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

相关标签:
10条回答
  • 2020-12-04 02:18

    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
    
    0 讨论(0)
  • 2020-12-04 02:20

    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.

    0 讨论(0)
  • 2020-12-04 02:22

    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.

    0 讨论(0)
  • 2020-12-04 02:26
    • Calculates the difference in days between the two dates
    • Calculates the difference in week numbers and year numbers, subtracts the week numbers and then multiplies the result by 2 to calculate number of non-workdays between the two dates. If year numbers are different calculation of 52 * year difference + week number.

    ((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

    0 讨论(0)
提交回复
热议问题