简体   繁体   中英

Sum of time difference - Oracle SQL

I have a table:

table1

col1    start_date_time                 end_date_time
Test1   01-06-19 11:43:35.927422000 AM  01-06-19 11:44:20.127907000 AM
Test2   01-06-19 11:44:28.703518000 AM  01-06-19 11:45:06.538883000 AM
Test3   01-06-19 11:42:18.784477000 AM  01-06-19 11:42:27.635102000 AM

I wrote a query which gives me the time difference:

select a.*, end_date_time - start_date_time exec_time from table1 a
order by exec_time desc;

Output Table

col1    start_date_time                 end_date_time                   exec_time
Test1   01-06-19 11:43:35.927422000 AM  01-06-19 11:44:20.127907000 AM  +00 00:00:44.200485
Test2   01-06-19 11:44:28.703518000 AM  01-06-19 11:45:06.538883000 AM  +00 00:00:37.835365
Test3   01-06-19 11:42:18.784477000 AM  01-06-19 11:42:27.635102000 AM  +00 00:00:08.850625

I need the sum like 00:01:29.

How can I sum the exec_time in SQL? I need to find the total time based.

Oracle does not support the aggregation of interval datatypes, which is a crying shame because that would be the easiest way to solve problems like this. However, the fiendish mind of Stew Ashton came up with a solution of converting intervals into numbers and back again.

select numtodsinterval(  
  sum(  
    (sysdate+(end_date_time - start_date_time) - sysdate) * 24 * 60 * 60
        + extract(second from (end_date_time - start_date_time)) 
              - trunc(extract(second from (end_date_time - start_date_time))) -- (*)
  )  
  , 'second'  
)  
from table1; 

Here is a demo on db<>fiddle .

(*) This line makes the answer accurate to microseconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM