在Oracle SQL 中根據營業時間計算時間
要在考慮營業時間限制的同時測量開始時間和結束時間之間經過的時間,我們需要將工作日限制納入我們的計算中。以下是在Oracle SQL 中實現此目的的方法:
根據營業時間調整直接計算:
此方法直接計算根據定義的營業時間進行調整的小時差:
SELECT task, start_time, end_time, ROUND( ( -- Calculate full weeks difference from start of ISO weeks. ( TRUNC( end_time, 'IW' ) - TRUNC( start_time, 'IW' ) ) * (10/24) * (6/7) -- Add full days for the final week. + LEAST( TRUNC( end_time ) - TRUNC( end_time, 'IW' ), 6 ) * (10/24) -- Subtract full days from days of the week before the start date. - LEAST( TRUNC( start_time ) - TRUNC( start_time, 'IW' ), 6 ) * (10/24) -- Add hours of final day + LEAST( GREATEST( end_time - TRUNC( end_time ) - 8/24, 0 ), 10/24 ) -- Subtract hours of the day before the range starts. - LEAST( GREATEST( start_time - TRUNC( start_time ) - 8/24, 0 ), 10/24 ) ) -- Multiply to give minutes instead of fractions of full days. * 24, 15 -- Number of decimal places ) AS work_day_hours_diff FROM your_table;
工作日分層查詢產生:
或者,我們可以為每個工作日產生一行併計算每天的小時數,然後將它們相加:
SELECT task, COALESCE( SUM( end_time - start_time ), 0 ) * 24 AS total_hours FROM ( SELECT task, GREATEST( t.start_time, d.column_value + INTERVAL '8' HOUR ) AS start_time, LEAST( t.end_time, d.column_value + INTERVAL '18' HOUR ) AS end_time FROM your_table t LEFT OUTER JOIN TABLE( CAST( MULTISET( SELECT TRUNC( t.start_time + LEVEL - 1 ) FROM DUAL WHERE TRUNC( t.start_time + LEVEL - 1 ) - TRUNC( t.start_time + LEVEL - 1, 'iw' ) < 6 CONNECT BY TRUNC( t.start_time + LEVEL - 1 ) < t.end_time ) AS SYS.ODCIDATELIST ) ) d ON ( t.end_time > d.column_value + INTERVAL '8' HOUR AND t.start_time < d.column_value + INTERVAL '18' HOUR ) ) GROUP BY task;
兩種方法都考慮星期一到星期六,08: 00至18:00為營業時間。如果您的營業時間不同,請務必調整查詢中的營業時間定義。
以上是如何在 Oracle SQL 中考慮營業時間來計算經過的時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!