Avg Time  Difference of Two timestamps in Oracle SQL

Hello Members,
  I am trying to find the average of Time Difference of two timestamp columns by order number. I need to show the average of the time difference in hours:mins format. I have is SQL Server , but unable to get this in Oracle SQL. Could anyone please let me know how I need to find the time difference of two timestamp columns and show them in hh:mm fomat and then take average of these differences and show them in hh:mm format.  Below is what I have tried in SQL server.
CREATE TABLE temp
startdate smalldatetime,
enddate smalldatetime
INSERT temp
SELECT '6/22/2013 19:00',
'6/22/2013 19:20'
UNION ALL
SELECT '6/22/2013 19:22',
'6/22/2013 19:44'
UNION ALL
SELECT '6/22/2013 19:45',
'6/22/2013 19:50'
UNION ALL
SELECT '6/22/2013 19:52',
'6/22/2013 20:02'
UNION ALL
SELECT '6/22/2013 20:05',
'6/22/2013 20:10'
UNION ALL
SELECT '6/22/2013 20:15',
'6/22/2013 20:20'
SELECT CAST
CAST
( SUM
DATEDIFF(MINUTE,startdate,enddate)
6*60
As float)
as varchar) + ':' +
cast
cast
cast
SUM
DATEDIFF(MINUTE,startdate,enddate)
6
as int )
% 60 as float )
as varchar ) AS avg_time_diff_in_hh_mm_format
FROM temp
Please let me know if you need additional information.
Thanks in Advance.

Thanks for the reply Frank,
  I have tried some similar lines with your suggested approach, please see below:
--DDL
CREATE TABLE XX_ORD_TIMES
(ORDER_NUM NUMBER(15),
         ACTUAL_START_DATE DATETIME,
         ACTUAL_FINISH_DATE DATETIME)
--Sample Data
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SFM-07', TO_DATE('06/20/2013 14:22:58', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/21/2013 07:58:55', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SFM-07', TO_DATE('06/21/2013 09:12:42', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/21/2013 09:18:15', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SFM-07', TO_DATE('06/20/2013 15:59:07', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('06/20/2013 17:06:17', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SVCEXT', TO_DATE('05/16/2013 11:56:05', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/24/2013 14:47:54', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SVCEXT', TO_DATE('05/07/2013 09:23:37', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/07/2013 13:00:14', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SVCEXT', TO_DATE('05/09/2013 14:06:08', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/22/2013 13:25:03', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SVCNEWPLON', TO_DATE('05/21/2013 13:17:45', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/24/2013 14:35:04', 'MM/DD/YYYY HH24:MI:SS'));
Insert into XX_ORD_TIMES
   (ORDER_NUM, ACTUAL_START_DATE, ACTUAL_FINISH_DATE)
Values
   ('SVCNEWPLON', TO_DATE('05/24/2013 09:00:04', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('05/29/2013 09:30:32', 'MM/DD/YYYY HH24:MI:SS'));
--Avg time diffs
SELECT  ORDER_NUM,
         ACTUAL_START_DATE
         ACTUAL_FINISH_DATE
                TO_NUMBER (
                   SUBSTR (
                      NUMTODSINTERVAL (
                         AVG (
                              CAST (ACTUAL_FINISH_DATE AS DATE)
                            - CAST (ACTUAL_START_DATE AS DATE)),
                         'DAY'),
                      2,
                      9))
              * 24
            + TO_NUMBER (
                 SUBSTR (
                    NUMTODSINTERVAL (
                       AVG (
                            CAST (ACTUAL_FINISH_DATE AS DATE)
                          - CAST (ACTUAL_START_DATE AS DATE)),
                       'DAY'),
                    12,
                    2))
         || ':'
         || CASE
               WHEN LENGTH (
                       TO_NUMBER (
                          SUBSTR (
                             NUMTODSINTERVAL (
                                AVG (
                                     CAST (ACTUAL_FINISH_DATE AS DATE)
                                   - CAST (ACTUAL_START_DATE AS DATE)),
                                'DAY'),
                             15,
                             2))) < 2
               THEN
                     '0'
                  || TO_NUMBER (
                        SUBSTR (
                           NUMTODSINTERVAL (
                              AVG (
                                   CAST (ACTUAL_FINISH_DATE AS DATE)
                                 - CAST (ACTUAL_START_DATE AS DATE)),
                              'DAY'),
                           15,
                           2))
               ELSE
                  TO_CHAR (
                     SUBSTR (
                        NUMTODSINTERVAL (
                           AVG (
                                CAST (ACTUAL_FINISH_DATE AS DATE)
                              - CAST (ACTUAL_START_DATE AS DATE)),
                           'DAY'),
                        15,
                        2))
            END
            AS TIME_DIFF
    FROM XX_ORD_TIMES
   GROUP BY ORDER_NUM,
         ACTUAL_START_DATE
         ACTUAL_FINISH_DATE
         order by 1;
Yes, I am trying to show the time difference of two timestamps ( finish date , start date ) in Hours:Mins  and also calculate the average of this Hours : Mins by ORDER_NUM .
Please advise.
Thanks again.

Similar Messages

  • How to measure time difference between two continous encoder pulse (PULSE A & PULSE B)

    im trying to figure out the time difference between two square
    wave pulse (PULSE A and PULSE B) from an encoder. I tried to modify many code but fail to capture thephase difference  for each pulse. the
    pulse only rise to 5V and fall to 0V like normal square wave pulse
    can you and all of experts here help me out with this?
    my problem
    1) Encoder pulse are continous (pulse A and pulse B)
    2) Square wave pulse have "0V" and "5V" please rapidly
    if possible someone show me correct method , Im using LABVIEW 7.1 and Hardware NI SCOPE (PCI 5102)
    your advice are highly appreciated
    among my idea as in attachment , but I failed to get it
    Attachments:
    Need to Get this wave.JPG ‏34 KB

    Hi Amirul,
    Check the attached JPG file. i think this will be use full to you
    Regards,
    Santhosh M

  • Difference between two timestamp.

    Hi,
    I want to find difference between two timestamp in minutes.
    Actually i want to retrieve difference between current timestamp and the timestamp taken from the table
    select log_time from serv_info where server_id = 1;
    Can anyone tell me the query to find difference between two timestamps in minutes.
    -haifriends

    SQL> WITH serv_in AS
         (SELECT SYSTIMESTAMP - 1 / 4 log_time,
                 SYSTIMESTAMP now
            FROM DUAL)
    SELECT log_time,
           now,
             24 * 60 * EXTRACT (DAY FROM (now - log_time))
           + 60 * EXTRACT (HOUR FROM (now - log_time))
           + EXTRACT (MINUTE FROM (now - log_time))
           + 1 / 60 * EXTRACT (SECOND FROM (now - log_time)) diff_in_minutes
      FROM serv_in
    LOG_TIME  NOW                                 DIFF_IN_MINUTES
    01-MRZ-07 01-MAR-07 03.47.42.107462 PM +01:00      360,001791

  • Need a sql query to get the difference between two timestamp in the format of hh:mm:ss.msec

    I have a database table where it keeps record of the transaction when it starts at StartTime and when it ends at EndTime. Both these entries are having the timestamp entries. Say for example, I have a tuple with Entries like 'Transaction A' starts at '2014-05-07
    20:55:03.170' and ends at '2014-05-08 08:56:03.170'. I need to find the difference between these two timestamps and my expected output is 12:01:00.000. Let me know how to achieve this ? 

    Hi,
    You can use below script which calculates difference as DD:HH:MM:SS. You can modify the same:
    DECLARE @startTime DATETIME
    DECLARE @endTime DATETIME
    SET @startTime = '2013-11-05 12:20:35'
    SET @endTime = '2013-11-10 01:22:30'
    SELECT [DD:HH:MM:SS] =
    CAST((DATEDIFF(HOUR, @startTime, @endTime) / 24) AS VARCHAR)
    + ':' +
    CAST((DATEDIFF(HOUR, @startTime, @endTime) % 24) AS VARCHAR)
    + ':' +
    CASE WHEN DATEPART(SECOND, @endTime) >= DATEPART(SECOND, @startTime)
    THEN CAST((DATEDIFF(MINUTE, @startTime, @endTime) % 60) AS VARCHAR)
    ELSE
    CAST((DATEDIFF(MINUTE, DATEADD(MINUTE, -1, @endTime), @endTime) % 60)
    AS VARCHAR)
    END
    + ':' + CAST((DATEDIFF(SECOND, @startTime, @endTime) % 60) AS VARCHAR),
    [StringFormat] =
    CAST((DATEDIFF(HOUR , @startTime, @endTime) / 24) AS VARCHAR) +
    ' Days ' +
    CAST((DATEDIFF(HOUR , @startTime, @endTime) % 24) AS VARCHAR) +
    ' Hours ' +
    CASE WHEN DATEPART(SECOND, @endTime) >= DATEPART(SECOND, @startTime)
    THEN CAST((DATEDIFF(MINUTE, @startTime, @endTime) % 60) AS VARCHAR)
    ELSE
    CAST((DATEDIFF(MINUTE, DATEADD(MINUTE, -1, @endTime), @endTime) % 60)
    AS VARCHAR)
    END +
    ' Minutes ' +
    CAST((DATEDIFF(SECOND, @startTime, @endTime) % 60) AS VARCHAR) +
    ' Seconds '
    Reference:
    http://sqlandme.com/2013/12/23/sql-server-calculating-elapsed-time-from-datetime/
    - Vishal
    SqlAndMe.com

  • How to write a query to get the time difference of two varchar type time columns

    Hi,
    I want to get the time difference between the two varchar type columns.please see the attached image for more details:
    My requirement is like:
    timestarted
    timeended
    timediff
    9:00:00
    10:00:00
    1:00
    9:15
    9:30:00
    0:15

    Storing time alone as VARCHAR2 value is a incorrect design. Always store it as DATE or TIMESTAMP.
    If you already have a messed up design and cant change it, then you need to convert your VARCHAR2 time into a DATE or TIMESTAMP and find the difference. I have converted it to TIMESTAMP and obtained the difference as INTERVAL.
    SQL> with t
      2  as
      3  (
      4  select '09:00:00' timestarted, '10:00:00' timeended from dual
      5  union all
      6  select '09:15:00' timestarted, '09:30:00' timeended from dual
      7  )
      8  select timestarted
      9       , timeended
    10       , (timeended - timestarted) day to second diff
    11    from (
    12          select to_timestamp('01011900' || timeended, 'ddmmyyyyhh24:mi:ss') timeended
    13               , to_timestamp('01011900' || timestarted, 'ddmmyyyyhh24:mi:ss') timestarted
    14            from t
    15         );
    TIMESTARTED                                        TIMEENDED                                          DIFF
    01-JAN-00 09.00.00.000000000 AM                    01-JAN-00 10.00.00.000000000 AM                    +00 01:00:00.000000
    01-JAN-00 09.15.00.000000000 AM                    01-JAN-00 09.30.00.000000000 AM                    +00 00:15:00.000000
    SQL>

  • Stopping a while loop using the time difference of two tick counts

    Hi Guys,
    I'm currently writing a code which test how long does it take for a formula node to perform its operation. The program uses a while loop to perform the calculation, and the program stops after calculating when tick count has reached 10 seconds. The program then displays the number of iterations it does in 10 seconds. 
    So initially I created 2 frames of sequence structure. In my first frame I have my initial tick count, and in my second frame I have my final tick count and the while loop. I used the subtract function and divide the output by 1000 to get the time difference. Then using the comparison function, I set if output > 10 then the program should stop, to do this I linked the output of the comparison function to the stop button inside the while loop. 
    However, when I tried to run the code, the program just didn't run. Hence I created a similar program which puts the last tick count in new frame sequence. When I ran this code, the program never stopped. 
    Do you guys have any idea what went wrong with my codes.
    Thank you!
    Erry
    Solved!
    Go to Solution.
    Attachments:
    1. Tick Count.vi ‏27 KB
    tickcoun2.vi ‏27 KB

    Dataflow!
    In both VI's the stop terminal of the while loop is controlled by a boolean whose source is ouside of the while loop.  So that loop will either run once, or run forever, depending on the value of the boolean that is calculated before the loop starts and shows up at the tunnel going into the loop.
    I would recommend looking at the online LabVIEW tutorials
    LabVIEW Introduction Course - Three Hours
    LabVIEW Introduction Course - Six Hours

  • How to compare two schemas in Oracle sql developer

    Hello,
    I need to compare both the data and schemas details (columns etc) between two schemas on different databases (connections).
    What is the easiest and most efficient way to do this? Hopefully in Oracle Sql Developer or Sql Plus?
    Thanks.

    In SQL Developer go to Tools -> Schema Diff !
    in SQL* Plus you will need to write PL/SQL for this.
    Amardeep Sidhu

  • Procedure execution time difference in Oacle 9i and Oracle 10g

    Hi,
    My procedure is taking time on
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 is 14 min.
    same procedure is taking time on oracle Release 9.2.0.1.0 is 1 min.
    1) Data is same in both environment.
    2) Number of records are same 485 rows for cursor select statement.
    3)Please guide me how to reduce the time in oracle 10g for procedure?
    i have checked the explain plan for that cursor query it is different in both enviroment.
    so i have analysis that procedure is taking time on cursor fetch into statement in oracle 10g.
    example:-
    create or replace procedure myproc
    CURSOR cur_list
    IS select num
    from tbl
    where exist(select.......
    EXECUTE IMMEDIATE 'ALTER SESSION SET SQL_TRACE = TRUE';
    EXECUTE IMMEDIATE 'ALTER SESSION SET TIMED_STATISTICS = TRUE';
    OPEN cur_list;
    LOOP
    FETCH cur_list INTO cur_list; -----My procedure is taking time in this statement only for some list number. there are 485 list number.
    end loop;
    TRACE file for oracle 10g is look like this:-
    call count cpu elapsed disk query current rows
    Parse 1 0.00 0.00 0 0 0 0
    Execute 1 0.37 0.46 0 2 0 0
    Fetch 486 747.07 730.14 1340 56500700 0 485
    total 488 747.45 730.60 1340 56500702 0 485
    ORACLE 9i EXPLAIN PLAN FOR cursor query:-
    Plan
    SELECT STATEMENT CHOOSECost: 2 Bytes: 144 Cardinality: 12                                         
         18 INDEX RANGE SCAN UNIQUE LISL.LISL_LIST_PK Cost: 2 Bytes: 144 Cardinality: 12                                    
              17 UNION-ALL                               
                   2 FILTER                          
                        1 TABLE ACCESS FULL SLD.P Cost: 12 Bytes: 36 Cardinality: 1                     
                   16 NESTED LOOPS Cost: 171 Bytes: 141 Cardinality: 1                          
                        11 NESTED LOOPS Cost: 169 Bytes: 94 Cardinality: 1                     
                             8 NESTED LOOPS Cost: 168 Bytes: 78 Cardinality: 1                
                                  6 NESTED LOOPS Cost: 168 Bytes: 62 Cardinality: 1           
                                       4 TABLE ACCESS BY INDEX ROWID SLD.L Cost: 168 Bytes: 49 Cardinality: 1      
                                            3 INDEX RANGE SCAN UNIQUE SLD.PK_L Cost: 162 Cardinality: 9
                                       5 INDEX UNIQUE SCAN UNIQUE SLD.SYS_C0025717 Bytes: 45,760 Cardinality: 3,520      
                                  7 INDEX UNIQUE SCAN UNIQUE SLD.PRP Bytes: 63,904 Cardinality: 3,994           
                             10 TABLE ACCESS BY INDEX ROWID SLD.P Cost: 1 Bytes: 10,480 Cardinality: 655                
                                  9 INDEX UNIQUE SCAN UNIQUE SLD.PK_P Cardinality: 9           
                        15 TABLE ACCESS BY INDEX ROWID SLD.GRP_E Cost: 2 Bytes: 9,447 Cardinality: 201                     
                             14 INDEX UNIQUE SCAN UNIQUE SLD.PRP_E Cost: 1 Cardinality: 29                
                                  13 TABLE ACCESS BY INDEX ROWID SLD.E Cost: 2 Bytes: 16 Cardinality: 1           
                                       12 INDEX UNIQUE SCAN UNIQUE SLD.SYS_C0025717 Cost: 1 Cardinality: 14,078      
    ORACLE 10G EXPLAIN PLAN FOR cursor query:-                                   
         SELECT STATEMENT ALL_ROWSCost: 206,103 Bytes: 12 Cardinality: 1                                         
         18 FILTER                                    
              1 INDEX FAST FULL SCAN INDEX (UNIQUE) LISL.LISL_LIST_PK Cost: 2 Bytes: 8,232 Cardinality: 686                               
              17 UNION-ALL                               
                   3 FILTER                          
                        2 TABLE ACCESS FULL TABLE SLD.P Cost: 26 Bytes: 72 Cardinality: 2                     
                   16 NESTED LOOPS Cost: 574 Bytes: 157 Cardinality: 1                          
                        14 NESTED LOOPS Cost: 574 Bytes: 141 Cardinality: 1                     
                             12 NESTED LOOPS Cost: 574 Bytes: 128 Cardinality: 1                
                                  9 NESTED LOOPS Cost: 573 Bytes: 112 Cardinality: 1           
                                       6 HASH JOIN RIGHT SEMI Cost: 563 Bytes: 315 Cardinality: 5      
                                            4 TABLE ACCESS FULL TABLE SLD.E Cost: 80 Bytes: 223,120 Cardinality: 13,945
                                            5 TABLE ACCESS FULL TABLE SLD.GRP_E Cost: 481 Bytes: 3,238,582 Cardinality: 68,906
                                       8 TABLE ACCESS BY INDEX ROWID TABLE SLD.L Cost: 2 Bytes: 49 Cardinality: 1      
                                            7 INDEX UNIQUE SCAN INDEX (UNIQUE) SLD.PK_L Cost: 1 Cardinality: 1
                                  11 TABLE ACCESS BY INDEX ROWID TABLE SLD.P Cost: 1 Bytes: 16 Cardinality: 1           
                                       10 INDEX UNIQUE SCAN INDEX (UNIQUE) SLD.PK_P Cost: 0 Cardinality: 1      
                             13 INDEX UNIQUE SCAN INDEX (UNIQUE) SLD.SYS_C0011870 Cost: 0 Bytes: 13 Cardinality: 1                
                        15 INDEX UNIQUE SCAN INDEX (UNIQUE) SLD.PRP Cost: 0 Bytes: 16 Cardinality: 1      
    so Please guide me how to reduce the time in oracle 10g for procedure?
    1) Is this envrionment setting parameter?
    2) I have to tune the query? but which is executing fine on oracle 9i?
    so how to decrease the execution time?
    Thanks in advance.

    SELECT l_nr
    FROM x.ls b
    WHERE b.cd = '01'
    AND b.co_code = '001'
    AND EXISTS (
    SELECT T_L
    FROM g.C
    WHERE C_cd = '01'
    AND C_co_code = '001'
    AND C_flg = 'A'
    AND C_eff_dt <= sysdate
    AND C_end_dt >=
    sysdate
    AND C_type_code <> 1
    AND C_type_code <> 1
    AND targt_ls_type = 'C'
    AND T_L <> 9999
    AND T_L = b.l_nr
    UNION ALL
    SELECT l.T_L
    FROM g.C C,
    g.ep_e B,
    g.ep ep,
    g.e A,
    g.lk_in l
    WHERE l.cd = '01'
    AND l.co_code = '001'
    AND l.cd = C.C_cd
    AND l.co_code = C.C_co_code
    AND l.C_nbr = C.C_nbr
    AND l.targt_ls_type = 'C'
    AND lk_in_eff_dt <=
    sysdate
    AND lk_in_end_dt >=
    ( sysdate
    + 1
    AND ( (logic_delte_flg = '0')
    OR ( logic_delte_flg IN ('1', '3')
    AND lk_in_eff_dt <> lk_in_end_dt
    AND l.cd = ep.C_cd
    AND l.co_code = ep.C_co_code
    AND l.C_nbr = ep.C_nbr
    AND l.ep_nbr = ep.ep_nbr
    AND l.cd = A.e_cd
    AND l.co_code = A.e_co_code
    AND l.e_nbr = A.e_nbr
    AND l.cd = B.cd
    AND l.co_code = B.co_code
    AND l.C_nbr = B.C_nbr
    AND l.ep_nbr = B.ep_nbr
    AND l.e_nbr = B.e_nbr
    AND l.ep_e_rev_nbr = B.ep_e_rev_nbr
    AND B.flg = 'A'
    AND EXISTS (
    SELECT A.e_nbr
    FROM g.e A
    WHERE A.e_cd = B.cd
    AND A.e_co_code = B.co_code
    AND A.e_nbr = B.e_nbr
    AND A.e_type_code ^= 8)
    AND C_type_code <> 10
    AND C.C_type_code <> 13
    AND l.T_L = b.l_nr)
    --yes index is same                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How to find the difference between two timestamp column

    Dear All,
    please Solve my issue,
    I have Table name Record which has the following columns,
    Empid in number column, dat in timestamp
    which has the following values
    Expand|Select|Wrap|Line Numbers
    empid dat
    ====== ====
    101 4/9/2012 9:48:54 AM
    101 4/9/2012 9:36:28 AM
    101 4/9/2012 6:16:28 PM
    101 4/10/2012 9:33:48 AM
    101 4/10/2012 12:36:28 PM
    101 4/10/2012 8:36:12 PM
    101 4/11/2012 9:36:28 AM
    101 4/11/2012 4:36:22 PM
    Here I need to display the following columns,
    empid,min(dat) as start,max(dat) as end and difference(max(dat)-min(dat) for each day,
    for eg,
    Empid Strart end difference
    101 4/9/2012 9:48:54 AM 4/9/2012 6:16:28 PM 8.28
    like this.
    Here 3 different days are exists so It should return 3 records with the above mentioned columns,
    Please Help me to get this.
    Thank you,
    Regards,
    Gurujothi
    Edited by: Gurujothi on Apr 25, 2012 4:45 AM

    >
    101 4/9/2012 9:48:54 AM 4/9/2012 6:16:28 PM 8.28
    >
    why 4/9/2012 9:48:54?
    why not 4/9/2012 9:36:28 AM ?
    SQL>
    SQL> with t as
      2  (select  101 empid, to_timestamp('4/9/2012 9:48:54 AM', 'dd/mm/yyyy hh:mi:ss AM') dat from dual union all
      3  select 101, to_timestamp('4/9/2012 9:36:28 AM', 'dd/mm/yyyy hh:mi:ss AM') dat from dual union all
      4  select 101, to_timestamp('4/9/2012 6:16:28 PM', 'dd/mm/yyyy hh:mi:ss PM') dat from dual union all
      5  select 101, to_timestamp('4/10/2012 9:33:48 AM', 'dd/mm/yyyy hh:mi:ss AM') dat from dual union all
      6  select 101, to_timestamp('4/10/2012 12:36:28 PM', 'dd/mm/yyyy hh:mi:ss PM') dat from dual union all
      7  select 101, to_timestamp('4/10/2012 8:36:12 PM', 'dd/mm/yyyy hh:mi:ss PM') dat from dual union all
      8  select 101, to_timestamp('4/11/2012 9:36:28 AM', 'dd/mm/yyyy hh:mi:ss AM') dat from dual union all
      9  select 101, to_timestamp('4/11/2012 4:36:22 PM', 'dd/mm/yyyy hh:mi:ss PM') dat from dual
    10  )
    11  select empid, min(dat) as start_dat
    12  , max(dat) as end_dat
    13  , max(dat)-min(dat) diff
    14  from t
    15  group by empid, trunc(dat)
    16  /
         EMPID START_DAT                                         END_DAT                                           DIFF
           101 04.09.12 09:36:28,000000000                       04.09.12 18:16:28,000000000                       +000000000 08:40:00
           101 04.11.12 09:36:28,000000000                       04.11.12 16:36:22,000000000                       +000000000 06:59:54
           101 04.10.12 09:33:48,000000000                       04.10.12 20:36:12,000000000                       +000000000 11:02:24
    SQL>

  • Query performance difference -- CPU time difference on two servers

    Two SQL servers, server A & B, Hardware information as below:
    Server A: Clustered. Two physical processors (4 cores). RAM 64GB, SQL Server max memory: 58GB.
    Server B: Standalone. One physical processor (4 cores). RAM 16GB, SQL Server max memory: 10GB.
    The two databases on A & B are identical (using backup & restore method), same query execution CPU time are different, it is slower on the cluster server with more CPU & Mmeory. I tried many times and all same result, I also tried run DBCC DROPCLEANBUFFERS
    & DBCC FREEPROCCACHE before running the query.
    When I run the query, on Server A (Slow one), CPU usage is at 20% ~30%. RAM usage is 14%. It is new set up environment so just me using it now.
    When I run the query on Server B (Fast one), CPU usage is 40%, RAM usage is 85%.
    Both two servers have SAN connected storage.
    Query execution plan is exactly same on two serers.
    Could someone give me some advise how to troubleshoot this problem? Any suggestion is appreciated a lot! Thanks a lot!
    FYI, Below are the statistics when running same query in same DB on two servers:
    Server A CPU & IO Statistics:
    SQL Server parse and compile time: 
       CPU time = 109 ms, elapsed time = 297 ms.
    (1005301 row(s) affected)
    Table 'PODT'. Scan count 1, logical reads 55184, physical reads 3, read-ahead reads 55180, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'MRICLDEFENT'. Scan count 0, logical reads 71898, physical reads 3, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'POHD'. Scan count 1, logical reads 103154, physical reads 3, read-ahead reads 103150, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
     SQL Server Execution Times:
    CPU time = 7769 ms,  elapsed time = 16693 ms.
    Server B CPU & IO Statistics:
    SQL Server parse and compile time: 
       CPU time = 32 ms, elapsed time = 39 ms.
    (1005301 row(s) affected)
    Table 'PODT'. Scan count 1, logical reads 55184, physical reads 3, read-ahead reads 55180, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'MRICLDEFENT'. Scan count 0, logical reads 71898, physical reads 3, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'POHD'. Scan count 1, logical reads 103154, physical reads 3, read-ahead reads 103150, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
     SQL Server Execution Times:
    CPU time = 3931 ms,  elapsed time = 14387 ms.                             

    hi, Vivian_Vivian
    i just want to ask you 
    which sql version do you use?
    have you ever tried xevent before??
    if you use the sql2k8 or latter you can try xevent out to find somgthing clues about your cpu time problem
    i provide you the script,pls post your output in the xevent here so that we could judge what  the head of the problem is
    USE [master]
    GO
    CREATE EVENT SESSION [TrackSQLWait] ON SERVER
    ADD EVENT sqlserver.sql_statement_starting (
        ACTION ( sqlserver.session_id, sqlserver.database_id,sqlserver.sql_text ,package0.collect_system_time)
        WHERE ( sqlserver.database_id = 7 ) ), --★Do
    ADD EVENT sqlserver.sql_statement_completed (
        ACTION ( sqlserver.session_id, sqlserver.database_id, sqlserver.sql_text ,package0.collect_system_time)
        WHERE ( sqlserver.database_id = 7 ) ), --★Do
    ADD EVENT sqlserver.error_reported (
        ACTION ( sqlserver.session_id, sqlserver.database_id, sqlserver.sql_text ,package0.collect_system_time)
        WHERE ( sqlserver.database_id = 7 ) ), --★Do
    ADD EVENT sqlos.wait_info (
        ACTION ( sqlserver.database_id, sqlserver.session_id, sqlserver.sql_text,sqlserver.plan_handle ,package0.collect_system_time)
        WHERE 
        ( duration > 1000
          AND ( ( wait_type > 31    -- Waits for latches and important wait resources (not locks) 
                                -- that have exceeded 10 seconds. 
                  AND ( ( wait_type > 47
                          AND wait_type < 54
                        OR wait_type < 38
                        OR ( wait_type > 63
                             AND wait_type < 70
                        OR ( wait_type > 96
                             AND wait_type < 100
                        OR ( wait_type = 107 )
                        OR ( wait_type = 113 )
                        OR ( wait_type > 174
                             AND wait_type < 179
                        OR ( wait_type = 186 )
                        OR ( wait_type = 207 )
                        OR ( wait_type = 269 )
                        OR ( wait_type = 283 )
                        OR ( wait_type = 284 )
                OR ( duration > 30000        -- Waits for locks that have exceeded 30 secs.
                     AND wait_type < 22
    ADD TARGET package0.asynchronous_file_target (  SET filename = 'E:\ExtendedEvent\TrackSQLWait.xel' ,
                                                    metadatafile = 'E:\ExtendedEvent\TrackSQLWait.xem' )
    WITH ( MAX_MEMORY = 4 MB ,
            EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS )
    GO
    ALTER EVENT SESSION [TrackSQLWait]
    ON SERVER
    STATE=START
    -- Query the Event data from the Target.
    SELECT  event_data.value('(event/@name)[1]', 'varchar(50)') AS [event_name] ,
            event_data.value('(event/data[@name="source_database_id"]/value)[1]',
                             'int') AS [source_database_id] ,
            OBJECT_NAME(event_data.value('(event/data[@name="object_id"]/value)[1]',
                                         'int')) AS [object] ,
            event_data.value('(event/data[@name="object_type"]/value)[1]',
                             'varchar(60)') AS [object_type] ,
            event_data.value('(event/data[@name="state"]/text)[1]', 'varchar(50)') AS [state] ,
            event_data.value('(event/data[@name="duration"]/value)[1]', 'bigint') AS [duration] ,
            event_data.value('(event/data[@name="cpu"]/value)[1]', 'bigint') AS [cpu] ,
            event_data.value('(event/data[@name="reads"]/value)[1]', 'bigint') AS [reads] ,
            event_data.value('(event/data[@name="writes"]/value)[1]', 'bigint') AS [writes] ,
            event_data.value('(event/data[@name="error"]/value)[1]', 'bigint') AS [error] ,
            event_data.value('(event/data[@name="severity"]/value)[1]', 'int') AS [severity] ,
            event_data.value('(event/data[@name="user_defined"]/value)[1]',
                             'varchar(5)') AS [user_defined] ,
            event_data.value('(event/data[@name="message"]/value)[1]',
                             'varchar(max)') AS [message] ,
            event_data.value('(event/data[@name="wait_type"]/text)[1]',
                             'varchar(250)') AS wait_typetype ,
            event_data.value('(event/data[@name="wait_type"]/value)[1]',
                             'varchar(250)') AS wait_typevalue ,
            event_data.value('(event/data[@name="max_duration"]/value)[1]',
                             'bigint') AS max_duration ,
            event_data.value('(event/data[@name="completed_count"]/value)[1]',
                             'bigint') AS [completed_count] ,
            event_data.value('(event/action[@name="plan_handle"]/value)[1]',
                             'varchar(max)') AS [plan_handle] ,
            DATEADD(hh, DATEDIFF(hh, GETUTCDATE(), CURRENT_TIMESTAMP),
                    event_data.value('(event/action[@name="collect_system_time"]/text)[1]',
                                     'datetime2')) AS [system_time] ,
            event_data.value('(event/action[@name="session_id"]/value)[1]',
                             'bigint') AS [session_id] ,
            event_data.value('(event/action[@name="sql_text"]/value)[1]',
                             'varchar(max)') AS [sql_text]
    FROM    ( SELECT    CAST(event_data AS XML) AS event_data
              FROM      sys.fn_xe_file_target_read_file('E:\ExtendedEvent\TrackSQLWait_*.xel',
                                                        'E:\ExtendedEvent\TrackSQLWait_*.xem',
                                                        NULL, NULL)
            ) AS tab
    WHERE   event_data.value('(event/data[@name="duration"]/value)[1]', 'bigint') > 100
            AND event_data.value('(event/@name)[1]', 'varchar(50)') LIKE 'wait_info'
    ORDER BY [system_time]
    ALTER EVENT SESSION [TrackSQLWait]
    ON SERVER
    STATE=STOP
    GO
    DROP EVENT SESSION [TrackSQLWait] ON SERVER
    please replacing the related parameter to fit for your situation
    thanks

  • How to get exact date and time difference?

    Hi,
    When i am using the below sql statement:
    SELECT (TO_DATE('7/27/2006 05:00:15 PM','MM/DD/YYYY HH:MI:SS PM') - to_Date('7/27/2006 8:30:13 AM','MM/DD/YYYY HH:MI:SS AM')) * 24 hours FROM DUAL;
    the output is:
    Hours
    8.50055555555556
    But Actually it is 8.30
    So how can i get exact days and time difference between two dates in Oracle?
    Thanks....
    Regards,
    Suman Sakinala
    Edited by: SSN on Sep 19, 2008 1:27 AM

    Or more clearly (this time I have my date_from and date_to the right way around hehe!)
    SQL> ed
    Wrote file afiedt.buf
      1  WITH t as (select TO_DATE('7/27/2006 05:00:15 PM','MM/DD/YYYY HH:MI:SS PM') as dt_to,
      2                    TO_DATE('7/27/2006 08:30:13 AM','MM/DD/YYYY HH:MI:SS AM') as dt_from FROM DUAL)
      3      ,d as (select (dt_to-dt_from)*24 as diff_hrs from t)
      4  -- end of dates
      5  SELECT TRUNC(diff_hrs) as hours
      6        ,TRUNC(((diff_hrs) - TRUNC(diff_hrs))*60) as mins
      7        ,TRUNC(((((diff_hrs) - TRUNC(diff_hrs))*60) - TRUNC(((diff_hrs) - TRUNC(diff_hrs))*60))*60) as secs
      8* FROM d
    SQL> /
         HOURS       MINS       SECS
             8         30          2
    SQL>

  • Date/Time difference based on working days

    Hi Guru's,
           I am having a problem getting the difference between two timestamps. A normal difference between 2 timestamps is possible however i would like to calculate the hour difference between 2 timestamps excluding public holidays, weekends and also after office hours. Is there a series of FM or a logic to extract this kind of info. Hope you guys can shed some light into the matter.
    Thanks in advance.
    Anand

    Hi,
    Use FM DATE_COMPUTE_DAY. DATE in MM/DD/YYYY format.
    This FM returns the date in form of weekday number ie the date which you give is tuesday then it will return 2.
    Give call log date and call handled date.
    eg A call is logded on tuesday 3.00 pm and handled on Thursday 10.a.m.
    First check the days difference from the return of this FM.
    IF the call handled date return - call loged date return is positive means no sat sun , if negative means sat and sun.
    then from call logged date time start counting the office hours till call handled time.
    Office hours can be easily calculated using 24 hours clock.
    For public holidays have to check whether between the twodates any public holiday if is there then subtract that much office hours.
    Hope this helps.
    Thanks,
    Niketa

  • Time differences

    Hi all,
    I am working out the difference between two timestamps and using SimpleDateFormat to turn it into the form "HH:mm:ss". It all works fine except for one bit. Say if i work out the difference between two times set 10 seconds apart i get an out: 01:00:10.
    Where's that extra hour coming from? I know i could easily knock it all down by an hour but i want to know why it's doing it so i can sort something out.
    I am simply subtracting the later time (both are long datatypes) from the older time, turning it into Date and using SimpleDateFormat.
    Any ideas?
    Thanks

    steve_costin wrote:
    I want to know how many seconds, minutes and hours elapsed between two dates (long datatypes).
    ThanksYou could take the timestamp difference (in milliseconds) and do the math yourself. Or you could use a package like joda time:
    http://joda-time.sourceforge.net/

  • Time difference - going mad...

    Hi all!
    I just need the difference between two timestamps but there's always one hour too much...
    private static SimpleDateFormat timerFormat = new SimpleDateFormat("HH:mm:ss");
    long startTime = System.currentTimeMillis();
    // Do some processing that takes a few minutes
    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(timerFormat.format(new java.util.Date(elapsedTime)));But this always gives me things like
    01:04:23
    I always thought a new Date(0) would give me
    Thu Jan 01 00:00:00 CET 1970
    but it always tells me
    Thu Jan 01 00:00:00 CET 1970
    I'm lost, please help me.
    Regards
    Carsten

    If this is really just a few minutes of processing, conversion into a Date object seems a bit of overkill. Just convert the elapsed time in milliseconds directly. Unless you need to time to go into a database I suppose..., but then why not just store the milliseconds time?

  • How to find the structural difference between two tables

    Hi all,
    How to find the structural difference between two tables .
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE 11.1.0.7.0 Production
    TNS for 32-bit Windows: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - Production
    Thanks,
    P Prakash

    you could try something similar to this, for each table pair that you want to compare:
    SELECT 'TABLE_A has these columns that are not in TABLE_B', DIFF.*
      FROM (
            SELECT  COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
          ) DIFF
    UNION
    SELECT 'TABLE_B has these columns that are not in TABLE_A', DIFF.*
      FROM (
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
          ) DIFF;that's assuming, column_name, data_type and data_length are all you want to compare on.

Maybe you are looking for