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

Tags: Database

Similar Questions

  • 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!

  • 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 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

  • 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.

  • HP Office Jet Pro 8600 help how do I enlarge the print on an original when it is in copy mode?

    I find it on my help screen how do I enlarge the print on a copy of an original document that I want to copy. I have Windows 7 on my computer and printer is HP Office Jet Pro 8600 wireless. I have a printer HP (3 in 1 officejet) before and it was much more user friendly. Is to use the online mode?

    Here is a link to the user manual. To get the possibility to enlarge the copies, press this option on the display of the printer, then tap SETTINGS and then select resize, use the right arrow key to scroll through the sizing options on the printer. Changing the settings of copy is covered on page 59 and 60 in the manual. I hope this helps.

  • How do I know the difference between level data line in 2 dump files.

    Hello
    I had 2 dump files export different databases (to which I have access).
    They got the same tables and the same number of lines.
    How to compare data in tables (in the dump files).

    See you soon,.
    Malika

    user9131570 wrote:
    Hello
    I had 2 dump files export different databases (to which I have access).
    They got the same tables and the same number of lines.
    How to compare data in tables (in the dump files).

    See you soon,.
    Malika

    Why you want to do? What the company need? Without import it, it's not not possible to read the dump file *.

    Aman...

    * If you are using Data pump, you can make a sql file and can see items from the dump file.

  • 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;
        /

  • 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.

  • FormCalc - how to calculate the difference between the two fields datetime in hh: mm?

    Hello!

    I am building a form of time sheet in which I need to calculate the difference between the start and end times and present the result.

    I'm trying to do with FormCalc but if it is easier with JS is ok too.

    So that's what I did on the total field, by using the calculate on a NUMERIC field called decimalValue event:

    elapsed = Time2Num (endTime.formattedValue, "HH: mm")-Time2Num (startTime.formattedValue, "HH: mm")

    And then I tried to convert a time field:

    Total = decimalValue.rawValue;

    $.formattedValue = Num2Time (total, "HH: mm")

    Well, it doesn't work, it gives me crazy results in the datetime (total) field. If I type 09:00 and 09:30, the final result is... 22:30. Huh?

    Please, could someone help me understand how this thing works?

    Thanks a lot for the tips!

    Marcos

    Hi Marcos,

    Here are some examples:

    https://Acrobat.com/#d=kCPIgVkd09qrx6h-WRXxbQ

    https://Acrobat.com/#d=EsWqBMBt3sgEXnMSsK5pRA

    Hope that helps,

    Niall

  • Need help to calculate the difference between times

    Hi all

    I have two fields that stores just the hour in 24-hour ex: 08:00 and 20:00 now I want to calculate the difference between two times

    Kindle help me

    Thanks for your help

    Thank you
    Ravi

    Hello

    diiference in hours

    SQL> WITH T AS (SELECT '08:00' ST_TIME, '20:00' END_TIME FROM DUAL)
      2  SELECT (TO_DATE (END_TIME, 'HH24:MI') - TO_DATE (ST_TIME, 'HH24:MI')) * 24 DIFF_HOURS
      3    FROM T;
    
    DIFF_HOURS
    ----------
            12
    
    SQL> 
    

    G.

  • Watch does not recognize the weight class as exercise-how can you add the duration of activity manually because none of the presets eg elliptical etc. is appropriate. Also does not count calories for example 35 when the rest of the group is around 500

    Look does not recognize the weight class as exercise-how can you add the duration of activity manually because none of the presets etc for example elliptical is appropriate and therefore do not count toward the daily goal. Also does not count calories for example 35 when the average of the others in the group is around 500.

    Hello

    When you use the application of the training session, choose the type of activity that best fits your business. For anything else - like weight - select the other category.

    During the follow-up of one year to the next helps:

    • Activity app will credit the ring of progress of exercise with one minute for every minute of the workout.
    • Active calories will be based on the data recorded by the heart rate sensor or a brisk walk, whichever is greater.

    Note, however, that the heart rate sensor is likely to give better results for the workouts that involve rhythmic (for example running) rather than the irregular movements.

    More information:

    Use of the workout on your Apple Watch - Apple Support

  • How can I calculate the total time in java?

    Hello!

    I need to calculate the total time!

    For example I start time:
    Format formatter1;
    Date date1 = new Date();
    formatter1 = new SimpleDateFormat("hh:mm:ss");
    Dim startTime = formatter1.format (date1);
    startTime = "14:20:40.

    And I have finishing time:
    Format formatter2;
    Date2 date = new Date();
    formatter2 = new SimpleDateFormat("hh:mm:ss");
    String finishTime = formatter2.format (date2);
    finishTime = '08:30:55;



    Also, having calculated manually, I get the total time: '18:10:15.

    How can I calculate the total time in java? (Using formatter1 and formatter2 I guess)

    What I need is to print 'total 18:10:15 '.

    Thank you!

    800512 wrote:
    I did the following, but I think something's wrong here:

    I've defined before: Date date1 = new Date(); Date2 date = new Date();
    And it should be exactly 5 seconds between them.

    I found the delta between date1 and date2:

    Format formatter = new SimpleDateFormat("HH:mm:ss");
    timeInMilliFromStart long = date1.getTime () - date2.getTime ();
    Date date3 = new Date (timeInMilliFromStart);
    String timeInSecFromStart = formatter.format (date3);

    and I still get
    timeInSecFromStart = 02:00:05

    But it should be exactly 00:00:05.

    What is a problem?

    Because, as I said, a Date to measure a moment in time, not a period. So when you have 5000 ms, and you that transform a Date, this means that 5 seconds after the time, which equals 00:00:05.000 01/01/1970 GMT.

    As I said, if you are not currently in GMT, then you must set the DateFormat GMT TZ. Right now, it's to show you the time in your TZ. If you have included the date in your SimpleDateFormat, you would see the 01/01/1970 or 31/12/1969, function that TZ you find.

    Bottom line: you try to use these classes in a sense they are not intended for, and while you can get the results you want for a limited set of entries if you understand how these classes and how to work with it, it is a fragile approach and comes with all sorts of warnings warning.

  • How do we calculate the growth of the database?

    I have the situation where I have to calculate the growth of the database. I'm new to this business. We have implemented new indexes on the database of production where it took freespace all that remains. So, we have increased tablespace because we still have a few clues more to compile. Unfortunately, we ran out of space on the server. I asked for more space on the server that is to say 50% of the current database size. Of course, there are other databases on the same server and management wants to know why I need that a lot of space. Now my question is

    1. How do we calculate the growth of the database?
    2. How do we know how much table space is necessary for the given index.
    3. while maintaining growth increased from DB in calculating how we predict future growth.

    Any help much appreciated. Thank you.

    Hello

    Please visit the following link.

    http://www.DBA-Oracle.com/t_database_growth_reports.htm

    I hope this will help you.

    Thank you

  • How can I fix the link between adobe and windows if I see .pdf not win32 application

    How can I fix the link between adobe and windows if I see .pdf not win32 application, without the disc?

    "Adobe" is the name of the company that provides a great many different applications.

    Adobe Reader is free and allows you to view pdf files.

    Adobe Acrobat is expensive and allows you to create, edit and view pdf files.

    Assuming that you are referring to the reader, uninstall all the versions of it using the control panel > add or remove programs.  Then either

    1. go to http://get.adobe.com/reader/?promoid=BUIGO and download the current version (remember to uncheck the box to install McAfee Security Scan Plus.

    or

    2. go to http://www.foxitsoftware.com/Secure_PDF_Reader/ and download Foxit Reader, a small pdf reader and many more.

    Then, install the reader that you have downloaded.

Maybe you are looking for

  • Why showing this msg cannot be downloaded at this time App Store

    Can not be downloaded right now. Why the display of this message. I can't to download any application

  • Is there a way to get iPhoto to Yosemite?

    Is there a way to get iPhoto to Yosemite? I was annoyed with changes before but it's just because change is difficult, you have your ways of doing things, has worked on the system and used to it. It's different. Pictures is simply bad. I shouldn't wo

  • Satellite A200 - 1 GB block during the bios update - will not turn on

    Need help please, I was updating of the bios. And the process is stopped at: 2/18. I wait an hour and i decided to turn off the laptop. Know I can't turn on. Nothing happens. Anyone know how the recovery mode? Thank you (Sorry for my bad English)

  • Hearing of MFI-help - cancelled

    I had to resound hearing aids Linx, but not more (1 year +). Echo deleted app. However such aid always appear under settings/accessibility/hearing aids - list of devices (such as the pair) and seems as if IOS is still "looking" for them. How to untie

  • Data in table, overwritten by the null value

    I work on writing a VI that simulttaneously reading speed and pressure, then record them on separate tables.  Hit a wall at about 90% of the way through. The data (represented by random numbers for testing sake) comes in this central loop case then a