Function to get number of weekdays between two dates excluding holidays

前端 未结 3 1039
南笙
南笙 2020-12-11 13:17

I have an sql query that casts 2 dates and checks if they are equal. But even though the dates are equal, i dont get the result.

create or replace 
FUNCTION          


        
相关标签:
3条回答
  • 2020-12-11 14:11

    I posted most of this in your earlier question. You do not need to loop through the days and check each one individually. You should be able to calculate the number of week days and then just subtract number of distinct days in your table:

    CREATE FUNCTION getWorkingDays (
      in_start_date IN  DATE,
      in_end_date   IN  DATE
    ) RETURN NUMBER
    IS
      p_start_date   DATE;
      p_end_date     DATE;
      p_working_days NUMBER;
      p_holiday_days NUMBER;
    BEGIN
      IF in_start_date IS NULL OR in_end_date IS NULL THEN
        RETURN NUll;
      END IF;
    
      p_start_date := TRUNC( LEAST( in_start_date, in_end_date ) );
      p_end_date   := TRUNC( GREATEST( in_start_date, in_end_date ) );
    
      -- 5/7 * ( Number of weekdays between monday of the week containing the start date
      --         and monday of the week containing the end date )
      -- + LEAST( day of week for end date, 5 )
      -- - LEAST( day of week for start date, 5 )
      p_working_days := ( TRUNC( p_end_date, 'IW' ) - TRUNC( p_start_date, 'IW' ) ) * 5 / 7
                        + LEAST( p_end_date - TRUNC( p_end_date, 'IW' ) + 1, 5 )
                        - LEAST( p_start_date - TRUNC( p_start_date, 'IW' ) + 1, 5 );
    
      SELECT COUNT( DISTINCT TRUNC( HOLIDAY_DATE ) )
      INTO   p_holiday_days
      FROM   ATL_JOB_HOLIDAY jh
      JOIN   ATL_MASTER_JOB mj
      ON     MJ.MASTER_JOB_ID    = JH.MASTER_JOB_ID
      WHERE  TRUNC(HOLIDAY_DATE) BETWEEN p_start_date AND p_end_date;
    
      RETURN p_working_days - p_holiday_days;
    END;
    /
    

    (Note: HOLIDAY_DATE, in_start_date and in_end_date are TRUNCated before comparing so that all the time components are effectively ignored.)

    0 讨论(0)
  • 2020-12-11 14:14

    Your where clause is like this:

    where trunc(HOLIDAY_DATE) = to_date('2016-APR-11', 'yyyy-mon-dd')
    
    0 讨论(0)
  • 2020-12-11 14:16

    I am guessing that you are using Oracle. If so, the DATE data type contains a time component. This is rather confusing. But you could do what you want using TRUNC() rather than CAST():

    SELECT TRUNC(HOLIDAY_DATE), DATE '2011-04-16'  --into DAY_COUNT
    FROM ATL_JOB_HOLIDAY jh JOIN
         ATL_MASTER_JOB mj
         ON mj.MASTER_JOB_ID = jh.MASTER_JOB_ID
    WHERE TRUNC(HOLIDAY_DATE) = DATE '2011-04-16';
    

    Note also the preference for ANSI standard dates and for table aliases.

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