sql >> データベース >  >> RDS >> Oracle

週末、および午後6時から午後9時を除外するOracleクエリ

    日数の差を直接計算できます(私の回答こちら から採用) ):

    SELECT start_date,
           end_date,
           ROUND(
             (
               -- Calculate the full weeks difference from the start of ISO weeks.
               ( TRUNC( end_date, 'IW' ) - TRUNC( start_date, 'IW' ) ) * (9/24) * (5/7)
               -- Add the full days for the final week.
               + LEAST( TRUNC( end_date ) - TRUNC( end_date, 'IW' ), 5 ) * (9/24)
               -- Subtract the full days from the days of the week before the start date.
               - LEAST( TRUNC( start_date ) - TRUNC( start_date, 'IW' ), 5 ) * (9/24)
               -- Add the hours of the final day
               + LEAST( GREATEST( end_date - TRUNC( end_date ) - 9/24, 0 ), 9/24 )
               -- Subtract the hours of the day before the range starts.
               - LEAST( GREATEST( start_date - TRUNC( start_date ) - 9/24, 0 ), 9/24 )
             )
             -- Multiply to give minutes rather than fractions of full days.
             * 24 * 60
           ) AS work_day_mins_diff
    FROM   table_name;
    

    サンプルデータの場合:

    CREATE TABLE table_name ( start_date, end_date ) AS
    SELECT DATE '2020-12-30' + INTERVAL '00' HOUR, DATE '2020-12-30' + INTERVAL '12' HOUR FROM DUAL UNION ALL
    SELECT DATE '2020-12-30' + INTERVAL '18' HOUR, DATE '2020-12-30' + INTERVAL '20' HOUR FROM DUAL UNION ALL
    SELECT DATE '2020-12-30' + INTERVAL '17:30' HOUR TO MINUTE, DATE '2020-12-30' + INTERVAL '21:30' HOUR TO MINUTE FROM DUAL UNION ALL
    SELECT DATE '2021-01-01' + INTERVAL '00' HOUR, DATE '2021-01-04' + INTERVAL '00' HOUR FROM DUAL UNION ALL
    SELECT DATE '2021-01-02' + INTERVAL '00' HOUR, DATE '2021-01-04' + INTERVAL '00' HOUR FROM DUAL UNION ALL
    SELECT DATE '2020-12-28' + INTERVAL '00' HOUR, DATE '2021-01-04' + INTERVAL '00' HOUR FROM DUAL UNION ALL
    SELECT DATE '2020-12-28' + INTERVAL '00' HOUR, DATE '2020-12-29' + INTERVAL '00' HOUR FROM DUAL;
    

    出力:

    ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS (DY)';を使用 )

    db <> fiddle こちら




    1. データベース設計:口座残高の計算

    2. 不正なMySQLダンプをインポートするときに行をスキップする方法

    3. Base64イメージがデータベースから選択してエンコードするときに検出される速度低下

    4. Express.jsとMySQLモデル+検証