4

我正在尝试减去两个日期并期望返回一些浮动值。但我得到的回报如下:

+000000000 00:00:07.225000

将该值乘以 86400(我想以秒为单位)得到更奇怪的返回值:

+000000007 05:24:00.000000000

任何的想法?我怀疑这与类型转换有关。

4

2 回答 2

7

我猜你的列被定义为timestamp而不是date.

减去时间戳的结果是一个interval,而减去date列的结果是一个数字,表示两个日期之间的天数。

这记录在手册中: http:
//docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

因此,当您将时间戳列转换为日期时,您应该得到您期望的结果:

with dates as (
   select timestamp '2012-04-27 09:00:00' as col1,
          timestamp '2012-04-26 17:35:00' as col2
   from dual
)
select col1 - col2 as ts_difference,
       cast(col1 as date) - cast(col2 as date) as dt_difference
from dates;

编辑

如果您想转换间隔,例如秒数(作为数字),您可以执行以下操作:

with dates as (
   select timestamp '2012-04-27 09:00:00.1234' as col1,
          timestamp '2012-04-26 17:35:00.5432' as col2
   from dual
)
select col1 - col2 as ts_difference,
       extract(hour from (col1 - col2)) * 3600 +  
       extract(minute from (col1 - col2)) * 60 + 
       (extract(second from (col1 - col2)) * 1000) / 1000 as seconds
from dates;

上面的结果是55499.5802

于 2012-04-27T09:51:50.147 回答
0

阅读这篇文章: http ://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129

例子:

create table yourtable(
date1 date, 
date2 date
)
SQL> select datediff( 'ss', date1, date2 ) seconds from yourtable

   SECONDS 
---------- 
   6269539
于 2012-04-27T09:29:25.410 回答