sqloracle-database

How to modify query converting DATEDIFF to Oracle accepted syntax?


I have a query which calculates date difference calculated in minutes excluding weekends but syntax doesn't work in Oracle, please help.

SELECT
(   DATEDIFF(MINUTE, create_date, status_date)
    - ( DATEDIFF(wk, create_date,status_date)*(2*24*60)
        -- End on Sunday
        -(CASE WHEN DATEPART(dw, status_date)  = 1 THEN 24.0*60-DATEDIFF(minute,CONVERT(date,status_date),status_date) ELSE 0 END)
        -- Start on Saturday
        -(CASE WHEN DATEPART(dw, create_date) = 7 THEN DATEDIFF(minute,CONVERT(date,create_date),create_date) ELSE 0 END)
        -- End on Saturday
        +(CASE WHEN DATEPART(dw, status_date)  = 7 THEN DATEDIFF(minute,CONVERT(date,status_date),status_date) ELSE 0 END)
        -- Start on Saturday
        +(CASE WHEN DATEPART(dw, create_date) = 1 THEN 24.0*60-DATEDIFF(minute,CONVERT(date,create_date),create_date) ELSE 0 END)
    )
) as min_diff 
FROM TABLE_Name

Solution

  • Adapting my answer for number of business days difference between two dates to minutes, you can calculate it by:

    Like this:

    SELECT TO_CHAR( start_date, 'YYYY-MM-DD HH24:MI:SS "("DY")"') AS start_date,
           TO_CHAR( end_date, 'YYYY-MM-DD HH24:MI:SS "("DY")"') AS end_date,
           ROUND(
             (
               ( TRUNC( end_date, 'IW' ) - TRUNC( start_date, 'IW' ) ) * 5 / 7
             + LEAST( end_date - TRUNC( end_date,   'IW' ), 5 )
             - LEAST( start_date - TRUNC( start_date, 'IW' ), 5 )
             ) * 24 * 60,
             2
           ) AS Num_Week_Day_Minutes
    FROM   table_name;
    

    Which, for the sample data:

    CREATE TABLE table_name ( start_date, end_date ) AS
    SELECT DATE '2024-04-12' + INTERVAL '23:59:00' HOUR TO SECOND,
           DATE '2024-04-15' + INTERVAL '00:01:00' HOUR TO SECOND
    FROM   DUAL UNION ALL
    SELECT DATE '2024-04-05' + INTERVAL '00:00:00' HOUR TO SECOND,
           DATE '2024-04-15' + INTERVAL '00:00:00' HOUR TO SECOND
    FROM   DUAL UNION ALL
    SELECT DATE '2024-04-14' + INTERVAL '23:59:00' HOUR TO SECOND,
           DATE '2024-04-15' + INTERVAL '00:01:00' HOUR TO SECOND
    FROM   DUAL
    

    Outputs:

    START_DATE END_DATE NUM_WEEK_DAY_MINUTES
    2024-04-12 23:59:00 (FRI) 2024-04-15 00:01:00 (MON) 2
    2024-04-05 00:00:00 (FRI) 2024-04-15 00:00:00 (MON) 8640
    2024-04-14 23:59:00 (SUN) 2024-04-15 00:01:00 (MON) 1

    fiddle