How to get business days or hours between two dates

前端 未结 3 2158
走了就别回头了
走了就别回头了 2020-12-22 00:53

How can I calculate business hours or days between two dates in oracle 10g?

For example we have two dates; 14/08/2012 9:30 and 16/08/2012 12:00 And we have working h

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-22 01:00

    I just did something like that. Here is an sql code piece to calculate the work done between stime and etime by employees in a table T

    create table t ( NAME varchar(50), stime date, etime date, clockin number,clockout number );
    insert into t values ( 'JOHN', to_date( '18/12/2003 11:40','dd/mm/yyyy hh24:mi'), to_date( '22/12/2003 14:00', 'dd/mm/yyyy hh24:mi'),8, 17 );
    insert into t values ( 'JOHN', to_date( '19/12/2003 13:40','dd/mm/yyyy hh24:mi'), to_date( '21/12/2003 15:00', 'dd/mm/yyyy hh24:mi'),8, 17 );
    insert into t values ( 'TOM', to_date( '19/12/2003 13:40','dd/mm/yyyy hh24:mi'), to_date( '21/12/2003 15:00', 'dd/mm/yyyy hh24:mi'),8, 17 );
    
    
    with oo as (SELECT LEVEL-1 rn FROM dual CONNECT BY LEVEL <= 365) --JUST A TABLE WITH INTEGER RECORDS FROM 1 To 365 
    select
    t.NAME ,sum(least( trunc(stime)+18.5/24+rn, etime )-greatest( stime, trunc(stime)+9.5/24+rn))*24 as WorkHours -- Get workhours between 09:30-18:30 
    from oo
    inner join t on oo.rn < (trunc(etime)-trunc(stime)+1) 
          and to_char(stime+rn,'Dy') not in ( 'Sat', 'Sun' )  --For eliminating Weekends
          and to_char(trunc(stime)+rn,'DD.MM')  != '04.07'   -- For eliminating Holidays
    group by t.NAME 
    

    You can delete the group by line and remove the sum function to see how it works by generating rows for each day worked.

提交回复
热议问题