从另一个时间戳添加秒到时间戳

时间:2013-11-06 14:15:06

标签: oracle oracle11g oracle10g

我有两个时间戳:

说:

21.10.2013 00:00:23

21.10.2013 00:00:00

如何将时间戳1的23秒添加到第二个。

目前我的查询是这样的:

select count(1) 
from tbl where timestamp1 >= NVL((select MAX(TIMESTAMP2) + ("Seconds from TS 1") 
from tbl2), timestamp - 1);

2 个答案:

答案 0 :(得分:4)

尝试:

timestamp2  + (extract (second from timestamp1)/86400) 

答案 1 :(得分:2)

作为替代方案,您可以将第一个时间戳记中的秒数(或分钟和秒数,或整个时间部分)作为interval,并将其添加到第二个时间戳。

TRUNC(date) function采用一个决定精度的参数;如果你通过DD(默认值),那么它会将整个时间关闭,如果你通过HH24,那么它会保留小时数,但会删除分钟数以及关闭时间等等。结果是一个日期,但是如果您从时间戳中减去该结果,则结果为间隔(as the docs say)。

您可以看到使用此演示创建的间隔:

with t as (
  select to_timestamp('2013-11-06 09:10:11', 'YYYY-MM-DD HH24:MI:SS') as ts1
  from dual
)
select ts1,
  ts1 - trunc(ts1, 'MI') as second_interval,
  ts1 - trunc(ts1, 'HH24') as minute_interval,
  ts1 - trunc(ts1, 'DD') as hour_interval
from t;

TS1                     SECOND_INTERVAL MINUTE_INTERVAL HOUR_INTERVAL
----------------------- --------------- --------------- -------------
2013-11-06 09:10:11.000 0 0:0:11.0      0 0:10:11.0     0 9:10:11.0   

然后,您可以将间隔添加到其他时间戳:

with t as (
  select to_timestamp('2013-11-06 09:10:11', 'YYYY-MM-DD HH24:MI:SS') as ts1,
    to_timestamp('2013-10-31 00:00:00', 'YYYY-MM-DD HH24:MI:SS') as ts2
  from dual
)
select ts2 + (ts1 - trunc(ts1, 'MI')) as ts2_second_adj,
  ts2 + (ts1 - trunc(ts1, 'HH24')) as ts2_minute_adj,
  ts2 + (ts1 - trunc(ts1, 'DD')) as ts2_hour_adj
from t;

TS2_SECOND_ADJ          TS2_MINUTE_ADJ          TS2_HOUR_ADJ          
----------------------- ----------------------- -----------------------
2013-10-31 00:00:11.000 2013-10-31 00:10:11.000 2013-10-31 09:10:11.000 

SQL Fiddle

如果您获得的时间超过一部分,那么这可能比执行多个extract调用更简单,并且必须将它们除以正确的值(86400秒等)。这也保留了时间戳的小数秒,这可能是也可能不是。

此方法also works for DATE values,而extract版本则没有。{/ p>

相关问题