Oracle查询以获取两个日期之间的工作日数,不包括节假日

时间:2019-01-30 15:16:23

标签: sql oracle date oracle11g

我们正在使用Oracle 11。

在CASE WHEN语句中,我需要检查两个日期之间的天数是否大于3个工作日(因此不包括周末和节假日)。

    CASE WHEN end_date - start_date > 3  THEN 0  --> this includes weekend 
        and holidays
WHEN CODE = 1 THEN 1
WHEN CODE =2 THEN 2
ELSE 3
END AS MyColumn

说我有一个假期日历表,该表的HolidayDates列包含所有假期,例如:12/25 / 2018、12 / 31/2018等。

HolidayDates
12/25/2018
12/31/2018 

所以,如果

日期1 = 1/2/19(星期三)

Date2 = 18/27/18(星期四)

日期1和日期2之间的工作日数为3天(12 / 27、12 / 28和12/31)。

以下查询将获得不包括周末的工作日数。

如何在此查询中也排除假期?

SELECT TO_CHAR( start_date, 'YYYY-MM-DD "("DY")"') AS start_date,

   ( TRUNC( end_date, 'IW' ) - TRUNC( start_date, 'IW' ) ) * 5 / 7
   + LEAST( TRUNC( end_date   ) - TRUNC( end_date,   'IW' ) + 1, 5 )
   - LEAST( TRUNC( start_date ) - TRUNC( start_date, 'IW' ), 5 )
     AS Num_Week_Days
FROM   table_name;

谢谢。

1 个答案:

答案 0 :(得分:0)

this previous answer中的代码并将其从函数转换为查询可得出:

Oracle设置

CREATE TABLE Holidays ( HolidayDates ) AS
SELECT DATE '2018-12-25' FROM DUAL UNION ALL
SELECT DATE '2018-12-31' FROM DUAL;

CREATE TABLE table_name ( start_date, end_date ) AS
SELECT DATE '2018-12-21', DATE '2018-12-26' FROM DUAL UNION ALL
SELECT DATE '2018-12-28', DATE '2019-01-01' FROM DUAL;

查询

SELECT t.*,
       ( TRUNC( end_date, 'IW' ) - TRUNC( start_date, 'IW' ) ) * 5 / 7
       + LEAST( TRUNC( end_date   ) - TRUNC( end_date,   'IW' ) + 1, 5 )
       - LEAST( TRUNC( start_date ) - TRUNC( start_date, 'IW' ), 5 )
       - ( SELECT COUNT(1)
           FROM   holidays
           WHERE  HolidayDates BETWEEN t.start_date AND t.end_date
           -- Exclude any weekend holidays so we don't double count.
           AND    TRUNC( HolidayDates ) - TRUNC( HolidayDates, 'IW' ) <= 5
         )
       AS Num_Week_Days
FROM   table_name t;

输出

START_DATE | END_DATE  | NUM_WEEK_DAYS
:--------- | :-------- | ------------:
21-DEC-18  | 26-DEC-18 |             3
28-DEC-18  | 01-JAN-19 |             2
01-JAN-19  | 07-JAN-19 |             5

db <>提琴here