时间戳总计

问题描述

我有以下查询来计算总时间戳

SELECT SUM(TIME_SPENT) FROM
(
 select a - b as time_spent from tbl1 where name = 'xxx'
 union all
select c - d as time_spent from tbl2 where name= 'yyy'
)a;

查询返回结果为 +00 00:01:54.252000 但是整个查询返回错误为ORA-00932:数据类型不一致:预期的NUMBER到INTERVAL DAY秒。

了解它需要这样的东西

SELECT COALESCE (
(to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')) -
(to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS')),INTERVAL '0' DAY) FROM DUAL;

如何与从Timestamp类型列中检索数据的子查询一起实现?

解决方法

您不能在Oracle中求和INTERVAL DAY TO SECOND。我认为这是最受好评的开放功能请求之一。

您可以将TIMESTAMP转换为DATE值,然后得出的结果是天数差异。乘以24*60*60就是想获得秒数:

SELECT SUM(TIME_SPENT) * 24*60*60 FROM FROM
(
 select CAST(a AS DATE) - CAST(b AS DATE) as time_spent from tbl1 where name = 'xxx'
 union all
select CAST(d AS DATE) - CAST(d AS DATE) as time_spent from tbl2 where name= 'yyy'
);

或者您可以编写将INTERVAL DAY TO SECOND转换为秒的函数:

CREATE OR REPLACE FUNCTION GetSeconds(ds INTERVAL DAY TO SECOND) DETERMINISTIC RETURN NUMBER AS
BEGIN
    RETURN EXTRACT(DAY FROM ds)*24*60*60 
        + EXTRACT(HOUR FROM ds)*60*60 
        + EXTRACT(MINUTE FROM ds)*60 
        + EXTRACT(SECOND FROM ds);
END;

并像这样使用它:

SELECT SUM(TIME_SPENT),numtodsinterval(SUM(TIME_SPENT),'second')
(
 select GetSeconds(a-b) as time_spent from tbl1 where name = 'xxx'
 union all
select GetSeconds(c-d) as time_spent from tbl2 where name= 'yyy'
);
,

尝试使用以下查询

 SELECT sum(extract(second from time_spent)) FROM
 (
  select a - b as time_spent from test2 where name = 'xxx'
  union all
  select c - d as time_spent from tbl2 where name= 'yyy'
 )a;

好像time_spent列是表中的时间戳类型,并且它不能在Sum函数中传递正确的数据类型。使用提取功能从time_spent中获取秒。

,
Users
└── clementbolin
    └── go
        └── src
            ├── main.go
            └── src
                └── function.go