SQL to return the number of working days between 2 passed in dates

前端 未结 6 1614
礼貌的吻别
礼貌的吻别 2021-01-07 08:10

I need to write an sql query that returns the number of Working days (Monday - Friday) between two given dates.

I was wondering what would be the most efficient way

6条回答
  •  情书的邮戳
    2021-01-07 08:52

    Here is an example

    with given_days(d) as(
      select <> + level - 1
        from dual
      connect by level < = (<> - <>) + 1
    )
    select count(*)
      from given_days
    where to_char(d, 'DY', 'NLS_DATE_LANGUAGE=english') not in ('SUN', 'SAT')
    

    Demonstration

    HR\XE> with given_days as(
      2    select (to_date('&&1', 'dd.mm.yyyy') + level - 1) as g_day
      3      from dual
      4    connect by level < = (to_date('&2', 'dd.mm.yyyy') - to_date('&&1', 'dd.mm.yyyy')) + 1
      5  )
      6  select count(g_day) as cnt
      7    from given_days
      8  where to_char(g_day, 'DY', 'NLS_DATE_LANGUAGE=english') not in ('SUN', 'SAT');
    Enter value for 1: 10.10.2012
    old   2:   select to_date('&&1', 'dd.mm.yyyy') + level - 1
    new   2:   select to_date('10.10.2012', 'dd.mm.yyyy') + level - 1
    Enter value for 2: 17.10.2012
    old   4:   connect by level < = (to_date('&2', 'dd.mm.yyyy') - to_date('&&1', 'dd.mm.yyyy')) + 1
    new   4:   connect by level < = (to_date('17.10.2012', 'dd.mm.yyyy') - to_date('10.10.2012', 'dd.mm.yyyy')) + 1
    
      cnt                                                                     
    ----------                           
       6                                                                      
    

提交回复
热议问题