Calculate business hours between 2 dates with negative numbers

Hi all

I use a function to calculate the difference between 2 dates schedules. The function was taken and adapted from this thread:

Calculate business hours between two dates in a cursor

CREATE OR REPLACE
  FUNCTION get_bus_minutes_between(
                                   p_start_date DATE,
                                   p_end_date DATE
                                  )
    RETURN NUMBER
    IS
        v_return NUMBER;
    BEGIN
        with t as (
                   select  case level
                             when 1 then greatest(p_start_date,trunc(p_start_date) + 9 / 24)
                             else trunc(p_start_date) + level - 15 / 24
                           end start_dt,
                           case connect_by_isleaf
                             when 1 then least(p_end_date,trunc(p_end_date) + 20 / 24)
                             else trunc(p_start_date) + level - 4 / 24
                           end end_dt
                     from  dual
                     connect by level <= trunc(p_end_date) - trunc(p_start_date) + 1
                  )
        select  sum(greatest(end_dt - start_dt,0)) * 24 * 60 work_minutes
          into  v_return
          from  t
          where trunc(start_dt) - trunc(start_dt,'iw') < 5; -- exclude weekends
        RETURN v_return;
    END;
    /

I am running into an issue that when the p_end_date is before the p_start_date value the function returns the full time between the dates without regard for business hours. if the end_date is before the start date I get the expected result i.e. difference between the dates in business hours.

Using example dates of start 19th October 2012 13:00:00 and end 22nd october 2012 13:21:00 the business minutes are 681. However if i reverse the dates I get -4341.


Correct labour code is the following, I've annotated so that he could help someone else looking for a solution like this:

CREATE OR REPLACE
  FUNCTION get_bus_minutes_between(
                                   p_start_date DATE,  --these are the 2 dates passed into the function
                                   p_end_date DATE     --these are the 2 dates passed into the function
)
RETURN NUMBER
IS
v_return NUMBER;

        l_start  DATE;

        l_end    DATE;

        l_factor NUMBER;
    BEGIN

        IF p_start_date <= p_end_date THEN            --this IF section checks which of the 2 dates is the greatest

           l_start  := p_start_date;                  -- and then assigns the earliest date to p_start_date

           l_end    := p_end_date;

           l_factor := 1;

        ELSE   -- swap the dates around, and multiply the result by -1

           l_start  := p_end_date;

           l_end    := p_start_date;

           l_factor := -1;

        END IF;

        with t as (
                   select  case level
                             when 1 then greatest(l_start,trunc(l_start) + 9 / 24)  -- this sets the start of working hours
                             else trunc(l_start) + level - 15 / 24  --if the start time is adjusted this value must also be adjusted
                           end start_dt,
                           case connect_by_isleaf
                             when 1 then least(l_end,trunc(l_end) + 20 / 24)  -- this sets the end of working hours
                             else trunc(l_start) + level - 4 / 24  -- if the end time is adjusted this value must also be adjusted
                           end end_dt
                     from  dual
                     connect by level <= trunc(l_end) - trunc(l_start) + 1
                  )
        select  sum(end_dt - start_dt) * 24 * 60 work_minutes  -- this subtracts the 2 dates and then multiplies by hours and minutes
          into  v_return
          from  t
          where trunc(start_dt) - trunc(start_dt,'iw') < 5; -- this exclude weekends
        RETURN v_return * l_factor;  -- this gives the negative or positive results so you can see if it was completed before or after the required date.
    END;
    /

Tags: Database

Similar Questions

  • Calculate business hours between two dates in a cursor

    Hello, its me again (?).

    Yesterday, I got a solution to a problem here where I need to calculate the hours between two dates, excluding Sat/Sun and from 09:00 to 18:00. I'm now putting this login in a PL/SQL block, so I can calculate it for each record in a slider, all by looping.
    with t (start_date
           ,end_date
           )
    as (select  to_date('22-oct-2012 09:00:00','dd-mon-yyyy hh24:mi:ss') start_dt,
                           to_date('23-oct-2012 09:00:00','dd-mon-yyyy hh24:mi:ss') end_dt
        from dual
       )
    , hrs (dt) as
      (select start_date
       from   t
       union all
       select dt +1/24/60
       from   hrs
       where  hrs.dt < (select end_date-1/24/60 from t)
      )
    select count(*)/60
    from hrs
    where to_char(dt,'dy') not in ('sat','sun')
    and  to_number(to_char(dt,'hh24')) not between 18 and 23
    and  to_number(to_char(dt,'hh24')) not between 0 and 8
    /
    The logic above, I'm up here:
    FOR c_record IN c_1 LOOP
    //For each record, check if the two dates meet the criteria and then raise the counters accordingly
    select  to_date(c_record.REPORTADA,'dd-mon-yyyy hh24:mi:ss') INTO vFch1 FROM DUAL;
    SELECT  to_date(c_record.INICIOREAL,'dd-mon-yyyy hh24:mi:ss') INTO vFch2 FROM DUAL;
    
    IF ((vHoras > 2) AND c_record.PRIORIDAD=3) THEN
      vContOk :=vContOk + 0;
      vContBad := vContBad+1;
      vContOt   := vContOt+1;
    ELSE 
      vContOk :=vContOk +1;
      vContBad := vContBad+0;
      vContOt   := vContOt+1;
    END
        IF;
    
    IF ((vHoras > 4) AND c_record.PRIORIDAD=2) THEN
      vContOk :=vContOk + 0;
      vContBad := vContBad+1;
      vContOt   := vContOt+1;
    ELSE
      vContOk :=vContOk +1;
      vContBad := vContBad+0;
      vContOt   := vContOt+1;
    END IF;
    
    IF ((vHoras > 16) AND c_record.PRIORIDAD=1) THEN
      vContOk :=vContOk + 0;
      vContBad := vContBad+1;
      vContOt   := vContOt+1;
    ELSE
      vContOk :=vContOk +1;
      vContBad := vContBad+0;
      vContOt   := vContOt+1;
    END IF;
    
    END LOOP;
    I really don't like if the performance is horrible because it will run once a month and should spend only 40-100 records.
    However, I can't find a way to use this connection even in this case

    Could you help me?
    Thank you!

    Greetings,
    NACEUR

    N wrote:
    I need to calculate the number of minutes between two dates, only count the hours from 9 to 18hs.

    CREATE OR REPLACE
      FUNCTION get_bus_minutes_between(
                                       p_start_date DATE,
                                       p_end_date DATE
                                      )
        RETURN NUMBER
        IS
            v_return NUMBER;
        BEGIN
            with t as (
                       select  case level
                                 when 1 then greatest(p_start_date,trunc(p_start_date) + 9 / 24)
                                 else trunc(p_start_date) + level - 15 / 24
                               end start_dt,
                               case connect_by_isleaf
                                 when 1 then least(p_end_date,trunc(p_end_date) + 18 / 24)
                                 else trunc(p_start_date) + level - 8 / 24
                               end end_dt
                         from  dual
                         connect by level <= trunc(p_end_date) - trunc(p_start_date) + 1
                      )
            select  sum(greatest(end_dt - start_dt,0)) * 24 * 60 work_minutes
              into  v_return
              from  t
              where trunc(start_dt) - trunc(start_dt,'iw') < 5; -- exclude weekends
            RETURN v_return;
    END;
    /
    

    For example:

    SQL> select get_bus_minutes_between(
      2                                 to_date('20-oct-2012 13:00:00','dd-mon-yyyy hh24:mi:ss'),
      3                                 to_date('22-oct-2012 13:21:00','dd-mon-yyyy hh24:mi:ss')
      4                                ) work_minutes
      5    from dual
      6  /
    
    WORK_MINUTES
    ------------
             261
    
    SQL> 
    

    SY.

  • How to calculate the hours between two dates by the numbers

    If I update 09:00 start time 17:00 end time of shift in C3 and B3, how to use a D3 formula to calculate the number of hours between the two?  Then I can just copy down the lines for nth years...

    It is a spreadsheet of the part-time staff payroll.

    I'm sure that a lot of people out there have done that.

    Help, please.

    Thank you.

    Eddie

    What program of worksheet that you are using? Since you have a newer iMac running El Capitan, I can safely assume that you use NOT AppleWorks, which is a Power PC application that can run on any OS newer than the snow leopard, OS X 10.6.8.

    If you use numbers, try to repost your question in numbers for Mac forum. If you use Microsoft Excel, try posting in the Microsoft forums. LibreOffice also has community support.

  • Calculate the hours between two dates

    Hello

    I have a requirement to count the hours with 2 given timestamps, something like:
    SQL> select ((to_date('22-oct-2012 13:00:00','dd-mon-yyyy hh24:mi:ss') - to_date('20-oct-2012 13:00:00','dd-mon-yyyy hh24:mi:ss'))*24) B from dual ;
    
             B
    ----------
            48
    However, I wish it would be that simple. I just need to count the hours between two timestamps for the hours of work for example, 08:00 - 17:00, MONDAY to Friday (excluding weekends).
    So lets say I have to count the hours between two dates above the result should be 18 hours not 48 (4 hours on 20/oct, 9 hours on 21/oct to 5 hours 22/oct).
    How can I achieve this? Any idea will be useful.

    Thank you

    My query generates a list of all the hours between the start and end time, filters on the hours that are outside of the hours of work and then account for the remaining lines. Change that to partial hours must just be a case of replace the two occurrences of 1/24 with 24/01/60, then - as say you - Division COUNT (*) by 60.

    There may be performance issues using techniques of generation of line like this, if you put this in a query involving the joining of several lines of other tables (for example where the dates of beginning and end are derived from several employees?) or in several days. If you don't find it then count the number of whole days (taking weekends into account) between dates and work on the partial days after that it could be better. This would probably involve a lot of statements of case (which I don't have time to test it now).

    Ben

  • Count the number of hours between the dates off holiday/weekend

    Hi all

    I've not worked with dates and was recently asked to create a report where I am looking for the number of hours between two dates only count business days.

    So for example I have given as follows

    Created on 2011-03-30 15:00
    Treaty of 2011-03-30 15:03:46
    Filled 2011-04-01 17:25:02
    Posted 2011-04-01 17:45

    For a total of looking for the CREATION and dates

    50 hours and 45 minutes

    IM also trying to exclude weekends and holidays, I read around and was able to also find an array of dates where I main date, the HOLIDAY_IND column, and the column WEEKDAY_IND

    If the calendar table I have looks like

    CALENDER_DATE HOLIDAY_IND WEEKDAY_IND
    2011-03-31 YY
    2011-04-01 N Y
    2011-04-02 N N

    IM really very puzzled to know where to start

    I thought I'd try to write with PL/SQL, but I don't have access of the user to create procedures/functions, so looks like right up to SQL

    Any help is appreciated!

    Hello

    Depeneding on your data and your needs, you can do something like this:

    SELECT     created_DATE,
    ,     mailed_date
    ,     24 * ( (mailed_date - created_date)
              - (
                SELECT  COUNT (*)
                FROM        table_o_dates
                WHERE    main_date > created_date
                AND        main_date < TRUNC (mailed_date)
                AND        (   holiday_ind = 'Y'
                         OR  weekday_ind = 'N'
                      )
              )
               )               AS hours_between
    FROM     table_x
    ;
    

    I hope that answers your question.
    If not, post a small example of data (CREATE TABLE and only relevant columns, INSERT statements) for all tables and also post the results desired from these data.
    Explain, using specific examples, how you get these results from these data.
    Always tell what version of Oracle you are using.

    What do you do if created_date or mailed_date is not a working day? Examples in you data and results.

  • How to calculate the difference between a Date column and the Date yesterday in the analysis (in the formula in the column)

    . For example, I need to calculate the difference between a date column, 'Table_Name '. "' Column_Name ' and (Current_Date-1). I tried different ways to do this. But nothing seems to work.

    Try the below formula.

    Replace "Time". "" Date "with your column.

    TIMESTAMPDIFF (SQL_TSI_DAY, "Time". "Date", TIMESTAMPADD (SQL_TSI_DAY-1, CURRENT_DATE))

    Thank you!

  • String to the Array.vi worksheet with negative numbers

    I was exploring a program posted on the developer zone titled "ClipboardtoNumericArray.vi" and noticed that it substitute 0 for elements with negative numbers. The 'String to Array.vi worksheet"working with negative numbers? If so, how?

    The problem is that your negative sign is not a negative sign.  This is the code ASCII 150.  I'll call it something like a "long dash", that's why it does not recognize the LabVIEW code.  A negative real sign you have in part E-6 is code ASCII 45.  And also why same Excel treats as text rather than a number.

    Where did you get the CSV file from?

  • How to calculate the difference between 2 dates, but with interruptions and stops between

    Hello

    How can I calculate the difference in minutes between 2 dates but taking into account the existence of a table in the Appendix, so if between start_date and end_date arguments, there is no 'work time' then this part of the time will not be included in the total difference.

    Records of the time table example:

    Time_configuration start_hour end_day end_hour
    219:00307:00
    319:00407:00

    so for example first record said that on Monday you start at 19:00 and leave the next day at 7:00 and then save the same sort of thing.

    There is an event that I want to track how many minutes lasted. for example, this event began the day 2 at 19:00 and ended the day 3 at 21:00

    Theoretically, this event really lasted: 840 minutes. This 840 minutes are within the limits of the annex.

    Thanks in advance.

    The storage of the dates not as data type DATE in most cases is bad design. In addition, how do you know what day of the date is 2 at 19:00? East - Monday 2 November 2015 or Monday, March 7, 2016? It is the same for the event. In any case, assuming that both calendar and events don't extend over several weeks:

    According to schedule)
    Select time_configuration 2, 19:00 ' start_hour, end_day 3,' 07:00 ' end_hour of all the double union
    Select 3, 19:00 ', 4,' 07:00 ' double
    ),
    event like)
    Select event_id 1, time_configuration 2, 19:00 ' start_hour, end_day 3: 21:00 ' end_hour of the double
    )
    Select e.event_id,
    Sum)
    less (e.end_day + to_date (e.end_hour, 'HH24'), s.end_day + to_date (s.end_hour, 'hh24:mi')).
    greater (e.start_day + to_date (e.start_hour, 'HH24'), s.start_day + to_date (s.start_hour,'hh24:mi'))))
    ) * 24 * 60 minutes
    Appendix s,
    e event
    where e.start_day + to_date(e.start_hour,'hh24:mi')< s.end_day="" +="">
    and e.end_day + to_date(e.end_hour,'hh24:mi') > s.start_day + to_date(s.start_hour,'hh24:mi')
    E.event_id group
    /

    EVENT_ID MINUTES
    ---------- ----------
    1 840

    SQL >

    SY.

  • Calculate the hours between 2 business days

    Hi all

    Do a complex calculation on the days I do not know how to achieve this.

    Here is my case:

    I have a week of work with hours of work.

    Then there's this delivery time sheet for how long should be set an order ready to be delivered:

    Order1: max 5 hours of work

    Order2: max 8 working hours

    Order3: max 16 hours of work

    When an order is placed, the time of the order is recorded, and when an order has been set in ready to be delivered, this time is also registered.

    How to calculate the time difference between the time where an order has been placed and the time where the order has been on loan. Thereby also taking into account the working days and hours of work.

    Example: type order1 order was placed Tuesday at 15:00.

    Order has been fixed loan Wednesday at 14:00

    This means that to fix this ready order lasts 7 hours, which means that it is 2 hours time.

    CREATE TABLE REF_WORKDAYS
      (
        
        "WERKDAG"       VARCHAR2(15 ) NOT NULL ENABLE,
        "SOORT_WERKDAG" VARCHAR2(15 ) NOT NULL ENABLE,
        "BEGIN_TIJD"    VARCHAR2(10 ) NOT NULL ENABLE,
        "EIND_TIJD"     VARCHAR2(10 B) NOT NULL ENABLE,
        
      )
    

    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Monday','WORKINGDAY','08:00','16:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Tuesday','WORKINGDAY','08:00','16:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Wednesday','WORKINGDAY','08:00','16:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Thursday','WORKINGDAY','08:00','16:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Friday','WORKINGDAY','08:00','16:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Satrurday','WORKINGDAY','08:00','14:00');
    Insert into REF_WORKDAYS (WERKDAG,SOORT_WERKDAG,BEGIN_TIJD,EIND_TIJD) values ('Sunday','NOT-WORKINGDAY','08:00','16:00');
    
    COMMIT;
    

    create table glas_order
    
    (order_id number
    , order_desc varchar2(100) not null
    , order_type varchar2(10) not null
    , order_date date not null
    , order_ready date
    
    );
    

    Insert into GLAS_ORDER (ORDER_ID,ORDER_DESC,ORDER_TYPE,ORDER_DATE,ORDER_READY) values (1,'order bla','Order1',to_date('07-APR-15 09:00','DD-MON-RR HH24:MI'),to_date('08-APR-15 12:00','DD-MON-RR HH24:MI'));
    Insert into GLAS_ORDER (ORDER_ID,ORDER_DESC,ORDER_TYPE,ORDER_DATE,ORDER_READY) values (2,'order nice','Order1',to_date('14-APR-15 10:00','DD-MON-RR HH24:MI'),to_date('16-APR-15 16:00','DD-MON-RR HH24:MI'));
    Insert into GLAS_ORDER (ORDER_ID,ORDER_DESC,ORDER_TYPE,ORDER_DATE,ORDER_READY) values (3,'order ugly','Order2',to_date('18-APR-15 13:00','DD-MON-RR HH24:MI'),to_date('21-APR-15 09:00','DD-MON-RR HH24:MI'));
    
    COMMIT;
    

    Thank you

    Diana

    Select

    I like order_id

    such as length d

    order_type

    d decode(order_type,'Order1',5,'Order2',8)

    overtime

    of glas_order o

    model

    Reference r on

    (select

    WERKDAG w

    begin_tijd b

    e eind_tijd

    , (to_date (eind_tijd, 'HH24') - to_date (begin_tijd, 'HH24')) * 24 hard

    of ref_workdays

    where soort_werkdag = "WORKINGDAY")

    dimension (w)

    measures (b, e, hard)

    main m

    partition of (order_id I)

    size of (0 n)

    measures (0d, order_date, order_ready, cast (null as varchar2 (10)) as wday, order_type)

    iterate (1e6) rules until (iteration_number > = trunc(order_ready[0]) - trunc(order_date[0])))

    WDAY [0] = to_char (order_date [0] + iteration_number, 'FMDay', 'NLS_DATE_LANGUAGE = ENGLISH')

    , d [0] = d [0] +.

    case

    When trunc(order_date[0]) = trunc(order_ready[0]) - beginning and ready same day

    then presentv (r.b [wday [0]],)

    less (largest (order_ready [0], to_date (to_char (order_date [0], 'YYYYMMDD') | r.b [WDAY [0]], 'YYYYMMDDHH24:MI')), to_date (to_char (order_date [0], 'YYYYMMDD') | r.e [WDAY [0]],'YYYYMMDDHH24:mi'))))

    -bigger (to_date (to_char (order_date [0], 'YYYYMMDD') | r.b [WDAY [0]], 'YYYYMMDDHH24:MI'), least (order_date [0], to_date (to_char (order_date [0], 'YYYYMMDD') | r.e [WDAY [0]],'YYYYMMDDHH24:mi'))))))

    0) * 24

    When order_date [0] + iteration_number = order_date [0] - first day

    then presentv (r.b [wday [0]],)

    TO_DATE (to_char (order_date [0], 'YYYYMMDD') | r.e [WDAY [0]], 'YYYYMMDDHH24:MI')

    -bigger (order_date [0], to_date (to_char (order_date [0], 'YYYYMMDD') | r.b [WDAY [0]],'YYYYMMDDHH24:mi'))))

    0) * 24

    When trunc(order_date[0]) + iteration_number = trunc(order_ready[0]) - last day

    then presentv (r.b [wday [0]],)

    less (order_ready [0], to_date (to_char (order_ready [0], 'YYYYMMDD') | r.e [WDAY [0]],'YYYYMMDDHH24:mi'))))

    -to_date (to_char (order_ready [0], 'YYYYMMDD') | r.b [WDAY [0]], 'YYYYMMDDHH24:MI')

    0) * 24

    of another nvl (r.dur [wday [0]], 0)

    end

    )

    ORDER_ID DURATION ORDER_TYPE OVERTIME
    1 11 Order1 6
    2 22 Order1 17
    3 10 Order2 2

    Rewrittten party rules for readability purposes (more resources)

    measures (0d, order_date, order_ready, cast (null as varchar2 (10)) as to_date (null), (null) to_date, bd, order_type, wday ed)

    iterate (1e6) rules until (iteration_number > = trunc(order_ready[0]) - trunc(order_date[0])))

    WDAY [0] = to_char (order_date [0] + iteration_number, 'FMDay', 'NLS_DATE_LANGUAGE = ENGLISH')

    , comics [0] = to_date (to_char (order_date [0] + iteration_number, 'YYYYMMDD') | r.b [WDAY [0]], 'YYYYMMDDHH24:MI')

    , ed [0] = to_date (to_char (order_date [0] + iteration_number, 'YYYYMMDD') | r.e [WDAY [0]], 'YYYYMMDDHH24:MI')

    , d [0] = d [0] +.

    case

    When trunc(order_date[0]) = trunc(order_ready[0]) - beginning and ready same day

    then presentv (r.b [wday [0]],)

    less (largest (order_ready [0], [0] bd), ed [0])

    -Greatest (BD [0], least(ORDER_DATE[0],ED[0]))

    0) * 24

    When order_date [0] + iteration_number = order_date [0] - first day

    then presentv (r.b [wday [0]],)

    ED [0]

    -Greatest(ORDER_DATE[0],BD[0])

    0) * 24

    When trunc(order_date[0]) + iteration_number = trunc(order_ready[0]) - last day

    then presentv (r.b [wday [0]],)

    least(order_ready[0],ED[0])

    -bd [0]

    0) * 24

    of another nvl (r.dur [wday [0]], 0)

    end

    )

    Jubilee should be Saturday I guessed.

  • Help: How do I calculate the duration between 2 dates, when these dates on 2 rows?

    Hello

    We are 11g.

    We have a table with times recorded in a column. Then, each line as a different date value.
    There is no pb to order the query on this date column (obviously)

    Now, we need to calculate the period of time between 2 successive rows.
    I first thought to use a cursor, the cursor loop, compute and update the "duration" column
    It's the basic option

    Now, I would like to know if, by using a single query, I couldn't directly the calculation I want?

    Here is my example:
    WITH t AS (
    SELECT 'aaa' col1, to_date( '20100201 09:23:50', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'aaa' col1, to_date( '20100201 13:14:33', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'aaa' col1, to_date( '20100207 13:14:33', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'bbb' col1, to_date( '20100202 09:21:10', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'bbb' col1, to_date( '20100203 08:11:06', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'bbb' col1, to_date( '20100203 15:13:55', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    UNION
    SELECT 'bbb' col1, to_date( '20100210 10:14:27', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
    ) 
    SELECT col1, to_char( date1,'YYYYMMDD HH24:MI:SS') date1  FROM t
    ORDER BY col1, date1;
    Ideally, that's what I would get (if my math is correct)
    COL DATE1               DURATION
    --- ----------------- ----------
    aaa 20100201 09:23:50          0
    aaa 20100201 13:14:33      13843
    aaa 20100207 13:14:33     518400
    bbb 20100202 09:21:10          0
    bbb 20100203 10:11:06      89396
    bbb 20100203 15:13:55      18169
    bbb 20100210 17:14:27     612032
    I hope I'm clear!

    Thanks a lot in advance for your help
    Olivier

    Of course; It's easy with the use of the function analytic lag:

    WITH t AS (SELECT 'aaa' col1, to_date( '20100201 09:23:50', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'aaa' col1, to_date( '20100201 13:14:33', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'aaa' col1, to_date( '20100207 13:14:33', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'bbb' col1, to_date( '20100202 09:21:10', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'bbb' col1, to_date( '20100203 08:11:06', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'bbb' col1, to_date( '20100203 15:13:55', 'YYYYMMDD HH24:MI:SS') date1 FROM dual
               UNION ALL
               SELECT 'bbb' col1, to_date( '20100210 10:14:27', 'YYYYMMDD HH24:MI:SS') date1 FROM dual),
    t_diff as (SELECT col1,
                      to_char( date1,'YYYYMMDD HH24:MI:SS') date1,
                      (date1 - lag(date1, 1, date1) over (partition by col1 order by date1))*24*60*60 date_diff
               FROM   t)
    select col1,
           date1,
           sum(date_diff) over (partition by col1 order by date1) duration
    from   t_diff
    ORDER BY col1, date1;
    

    Published by: Boneist on February 15, 2010 16:39
    (I can't read; initially gave the cumulative total of the period. Oh!)

    ETA2: Take note of the additional parameters, I used in the lag() - the third parameterd manages what should be the value in the field if there is no previous rank, so there is no need to use nvl elsewhere in the application to handle this situation.

    Published by: Boneist on February 15, 2010 16:42

  • Hours between two dates

    Hi friends,

    I use the Oracle 10 g server.

    Can someone help me find hours of day remained wise room_no.

    create the table ROOM_OCCUPIED

    (

    PERSON_NAME VARCHAR2 (10),

    ROOM_NO VARCHAR2 (5).

    DATE OF CHECK_IN,

    DATE OF CHECK_OUT

    )

    insert into ROOM_OCCUPIED (ROOM_NO, CHECK_IN, PERSON_NAME, CHECK_OUT)

    values ('JB', ' 20', to_date (March 5, 2015 19:00 ',' dd-mm-yyyy hh24:mi:ss'), to_date (May 5, 2015 12:00 ',' dd-mm-yyyy hh24:mi:ss'));))

    insert into ROOM_OCCUPIED (ROOM_NO, CHECK_IN, PERSON_NAME, CHECK_OUT)

    values ('CHRISTOPER', ' 15', to_date (January 5, 2015 09:00 ',' dd-mm-yyyy hh24:mi:ss'), to_date (5 March 2015 10:00 ',' dd-mm-yyyy hh24:mi:ss'));))

    insert into ROOM_OCCUPIED (ROOM_NO, CHECK_IN, PERSON_NAME, CHECK_OUT)

    values ('BIBI', '35', to_date (May 5, 2015 13:10 ',' dd-mm-yyyy hh24:mi:ss'), null);

    insert into ROOM_OCCUPIED (ROOM_NO, CHECK_IN, PERSON_NAME, CHECK_OUT)

    values ('DEV', ' 20', to_date (5 March 2015 01:00 ',' dd-mm-yyyy hh24:mi:ss'), to_date (5 March 2015 05:00 ',' dd-mm-yyyy hh24:mi:ss'));))

    Select t.*, (Nvl (t.check_out, Sysdate) - t.check_in) * 24 Hrs

    of room_occupied t

    ORDER BY 2

    PERSON_NAME ROOM_NO CHECK_IN CHECK_OUT TOT_HRS_STAYED

    CHRISTOPER 15 5/1/2015 09:00 03/05/2015 10:00 49

    20 H 5/3/2015 19:00 05/05/2015 12:00 41

    DEV 20 5/3/2015 01:00 03/05/2015 05:00 4

    BIBI 35 5/5/2015 13:10 10.66888889

    I need output like below a day format

    Name of person room occupied_dt Hrs_stayed

    Christoper 15 24 05/01/2015

    Christoper 15 05/02/2015 24 hours

    Christoper 15 9hrs 05/03/2015

    - - - - - - - - -

    - - - - - - - - -

    - - - - - - - - -

    I run every day to Watch report

    Rgds,

    RDK

    Hi Rdk,

    Here is my path. I'm counting minutes and then round up to hours for a day of occupation. To get the hours for those who are not yet extracted, I used check_out nvl (checked_out, sysdate). If not wanted then just delete expression nvl .

    alter session set nls_date_format='dd-mm-yyyy'
    ;
    with occupation_minutes (person_name, room_no, check_in, check_out, occupied_dt, minutes) as (
      select
        person_name,
        room_no,
        check_in,
        nvl(check_out, sysdate) check_out,
        trunc(check_in) occupied_dt,
        1 minutes
      from room_occupied
      union all
      select
        person_name,
        room_no,
        check_in,
        check_out,
        trunc(check_in + minutes / 1440),
        minutes + 1
      from occupation_minutes
      where minutes < (check_out - check_in) * 1440
    )
    select
      person_name,
      room_no,
      occupied_dt,
      round(count(minutes) / 60) || 'hrs' Hrs_stayed
    from occupation_minutes
    group by
      person_name,
      room_no,
      occupied_dt
    order by
      person_name,
      occupied_dt
    ;
    
    session SET altered.
    PERSON_NAME ROOM_NO OCCUPIED_DT HRS_STAYED
    ----------- ------- ----------- -------------------------------------------
    BIBI        35      05-05-2015  11hrs
    BIBI        35      06-05-2015  8hrs
    CHRISTOPER  15      01-05-2015  15hrs
    CHRISTOPER  15      02-05-2015  24hrs
    CHRISTOPER  15      03-05-2015  10hrs
    DEV         20      03-05-2015  4hrs
    SIDHIQ      20      03-05-2015  5hrs
    SIDHIQ      20      04-05-2015  24hrs
    SIDHIQ      20      05-05-2015  12hrs                                     
    
    9 rows selected
    
  • Calculate elapsed hours between two time fields

    I have a form with fields TimeStart and TimeEnd. Both are formatted as field time in the format hh: mm tt. I also have a field called hours with the number format. Here is the Javascript code that I have in the section calculation Script custom field hours. Could someone tell me why it doesn't work? This script started as a date calculation script (work), and I changed to the calculation of hours instead of days.

    var strStart = this.getField("TimeStart").value;

    var strEnd = this.getField("TimeEnd").value;

    If (strStart.length & & strEnd.length)

    {

    var timeStart = util.scand ("h: mm tt", strStart);

    var timeEnd = util.scand ("h: mm tt", strEnd);

    diff var = timeEnd.getTime () - timeStart.getTime ();

    var hour = 60 * 60 * 1000;

    var h = Math.floor (diff/oneHour);

    Event.Value = hours;

    }

    of another event.value = 0;

    The order for the calculation of the fields is wrong, you need to update.

  • How to calculate an interval between two dates?

    Hi all

    I have two dates, and I need to know if the interval between the two is more than 30 days or not. I can't understand how to calculate this interval.
    Could someone help me?
    Thank you very much.

    See the following forumpost:

    Re: Calculation of difference in date in BPEL

    Kind regards

    Melvin

  • Excerpt from the hours between two dates

    Hello

    This is the value stored in the table of my database.

    I want to extract betwwen hours two dates. How can I extract it.

    I try to run like this

    Select to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM') double, but it gives the answer as the format 21:10:00.000000000 + 000000365

    I want simple hours, minutes, and seconds

    What is the format of this value as "dd-MON-yy."

    27 JANUARY 14 01.30.00.000000 PM

    26 JANUARY 14 06.22.32.170033 PM

    Use the Extract function. Like this.

    () AS T1 (C1)

    Select to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM') of double)

    SELECT EXTRACT (DAY OF C1) | ' DAYS '.

    EXTRACT (HOUR OF C1) | ' HOURS '.

    EXTRACT (MINUTE OF C1) | ' MINUTES '.

    EXTRACT (SECOND C1) | ' SECONDS

    FROM T1;

    OUTPUT:

    365 DAYS 21 HOURS 10 MINUTES 0 SECONDS

    If not try it.

    SELECT EXTRACT (DAY OF to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM')) | ' DAYS '.

    EXTRACT (HOUR FROM to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM')) | ' HOURS '.

    EXTRACT (to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM') MINUTE) | ' MINUTES '.

    EXCERPT ((SECOND from to_timestamp('27-JAN-14 05.30.00.000000 PM')-to_timestamp('26-JAN-13 08.20.00.000000 PM')) |) ' SECONDS

    DOUBLE;

    Post edited by: Parth272025

  • How to calculate the difference between two times by the NUMBERS

    I'm so bothered by the fact that I can't understand that.

    Cell B2 - 08:00

    Cell C2 - 10:50

    (How can cell D2 - I get this cell to calculate the difference and say 02:50?)

    I know it's probably one of the most basic operations, but for the life of me I can't understand it. The cells B2 and C2 are formatted for a 24-hour clock. But if I tell the system to just subtract the two, I get "0,118. Everything I find on the forum search goes beyond what I need. Can someone help me?

    Thank you

    Hi sapirs,

    Departure and arrival of the cells are in Date and time with Date format: no and time: 24-hour clock.

    Formula in D2 (fill down)

    = C2−B2

    The results become a duration format, but under automatic (numbers automatically worth this format)

    If you wish, you can change the cells of lasting results.

    What Data Format have your result cells?

    Kind regards

    Ian.

Maybe you are looking for