Oracle
 sql >> Baza danych >  >> RDS >> Oracle

Usuwanie nakładających się godzin z liczenia dni wolnych od pracy

Konfiguracja Oracle :

CREATE TABLE Trip_Dates ( Start_Date, End_Date ) AS
SELECT TO_DATE( '2016-02-01 04:00:00', 'YYYY-MM-DD HH24:MI:SS' ), TO_DATE( '2016-02-02 10:00:00', 'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL UNION ALL
SELECT TO_DATE( '2016-02-02 14:00:00', 'YYYY-MM-DD HH24:MI:SS' ), TO_DATE( '2016-02-06 20:00:00', 'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL UNION ALL
SELECT TO_DATE( '2016-02-01 01:00:00', 'YYYY-MM-DD HH24:MI:SS' ), TO_DATE( '2016-02-02 07:00:00', 'YYYY-MM-DD HH24:MI:SS' ) FROM DUAL;

Zapytanie :

WITH Dates ( dt, start_end ) AS (
  SELECT GREATEST( start_date, TRUNC( SYSDATE, 'MM' ) ),
         1
  FROM   trip_dates
  WHERE  start_date < ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 )
  AND    end_date > TRUNC( SYSDATE, 'MM' )
  UNION ALL
  SELECT LEAST( end_date, ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 ) ),
         -1
  FROM trip_dates
  WHERE  start_date < ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 )
  AND    end_date > TRUNC( SYSDATE, 'MM' )
  ORDER BY 1, 2
)
,range_start_ends ( dt, start_end, range_start, range_end ) AS (
  SELECT d.*,
         CASE
           WHEN start_end =  1
            AND SUM( start_end ) OVER ( ORDER BY dt ) = 1
           THEN dt
           ELSE NULL
            END,
         CASE
           WHEN start_end = -1
            AND SUM( start_end ) OVER ( ORDER BY dt ) = 0
           THEN dt
           ELSE NULL
            END
  FROM   Dates d
),
worked_days ( worked_days ) AS (
  SELECT range_end - LAG( range_start ) IGNORE NULLS OVER ( ORDER BY dt )
  FROM   range_start_ends
)
SELECT ( ADD_MONTHS( TRUNC( SYSDATE, 'MM' ), 1 )
        - TRUNC( SYSDATE, 'MM' ) -
        SUM( worked_days )
       ) * 24 AS unworked_hours
FROM   worked_days;

Wyniki :

UNWORKED_HOURS
--------------
           561 



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Pobieranie danych z tabeli za pomocą PL/SQL

  2. Zależności klienta Oracle.DataAccess

  3. Oracle Database BLOB do InputStream w Javie?

  4. ORACLE SQL LISTAGG nie zwraca oczekiwanego wyniku

  5. Jak pobrać komentarze z Oracle 11g za pomocą JDBC?