时差总和-Oracle SQL

时间:2019-06-01 12:00:29

标签: sql oracle date-arithmetic

我有一张桌子:

表1

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

我写了一个查询,给出了时差:

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

输出表

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

我需要像00:01:29这样的总和。

如何在SQL中汇总exec_time?我需要找到总时间。

1 个答案:

答案 0 :(得分:3)

Oracle不支持间隔数据类型的聚合,这真是令人遗憾,因为这将是解决此类问题的最简单方法。但是,the fiendish mind of Stew Ashton came up with a solution将间隔转换为数字然后再次返回。

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; 

这里是a demo on db<>fiddle

(*)这行使答案精确到微秒。