0

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

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 TO SECOND。

理解它需要这样的东西

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') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')), INTERVAL '0' DAY) FROM DUAL;

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

4

3 回答 3

2

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

您可以将其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'
);
于 2020-08-25T11:34:34.957 回答
0
with t(a,b) as (
  select timestamp'2014-09-22 16:00:00.000', timestamp'2014-09-23 16:00:00.001' from dual union all
  select timestamp'2014-09-22 16:00:00.000', timestamp'2014-09-24 16:00:00.001' from dual union all
  select timestamp'2014-09-22 16:00:00.000', timestamp'2014-09-25 16:00:00.001' from dual union all
  select timestamp'2014-09-22 16:00:00.000', timestamp'2014-09-26 16:00:00.001' from dual union all
  select timestamp'2014-09-22 16:00:00.000', timestamp'2014-09-27 16:00:00.001' from dual
)
select
                        sum( (date'1-1-1'+(b-a)*24*60*60 - date'1-1-1'))     as ssum_seconds_1,
                  round(sum( (date'1-1-1'+(b-a)*24*60*60 - date'1-1-1')), 3) as ssum_seconds_rounded,
 numtodsinterval( round(sum( (date'1-1-1'+(b-a)*24*60*60 - date'1-1-1')), 3), 'second') dsint
from t
/
于 2020-08-25T11:06:23.290 回答
0

尝试使用以下查询

 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 函数中传递正确的数据类型。使用 extract 函数从 time_spent 中获取 Seconds。

于 2020-08-25T11:02:18.650 回答