在 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中文网其他相关文章!