Want a SQL to get days between 2 date and exclude Saturday and Sunday in Oracle [duplicate]

佐手、 提交于 2019-12-25 07:47:10

问题


As the title said, I want to calculate days between 2 dates and exclude weekend(Saturday and Sunday) in Oracle, I have no idea about this at all, can anyone help give an example SQL?


回答1:


Try this. Change start_date and end_date as per your requirement.

If you want number of weekdays, use

  WITH test_data AS
  (
     SELECT TO_DATE('01-JAN-2014','DD-MON-YYYY') AS start_date,
            TO_DATE('31-DEC-2014','DD-MON-YYYY') AS end_date  
       FROM dual
  ), 
all_dates AS 
( SELECT td.start_date, td.end_date, td.start_date + LEVEL-1 as week_day
      FROM test_data td
   CONNECT BY td.start_date + LEVEL-1 <=  td.end_date)

   select count(*) from all_dates
    WHERE to_char(week_day, 'dy', 'nls_date_language=AMERICAN') NOT IN ('sun' , 'sat')

If you want the dates displayed, in the select clause, use

select week_day from all_dates

How it works:

  1. It start adding 1 day to start_date until you reach end_date, by using connect by/level in Oracle.
  2. It removes the days which are saturday or sunday

PS: Refered this answer for it




回答2:


How about simplifying

"Select * from emp where hiredate between To_date(f_date,'dd-mm-yyyy) and to_date(t_date, 'Dd-mm-yyyy') and to_char(hiredate,dy) not in('sat','sun')



来源:https://stackoverflow.com/questions/42596211/want-a-sql-to-get-days-between-2-date-and-exclude-saturday-and-sunday-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!