Subtracting timestamp in oracle returning weird data

筅森魡賤 提交于 2020-01-03 17:09:24

问题


I'm trying to subtract two dates and expecting some floating values return. But what I got in return is as below:

+000000000 00:00:07.225000

Multiplying the value by 86400 (I want to get the difference in second) is getting something even more strange value being returned:

+000000007 05:24:00.000000000

any idea? I'm suspecting is has something to do with type casting.


回答1:


I guess your columns are defined as timestamp rather than date.

The result of subtracting timestamps is an interval whereas the result of subtracting date columns is a number representing the number of days between the two dates.

This is documented in the manual:
http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042

So when you cast your timestamp columns to date, you should get what you expect:

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;

Edit:

If you want to convert the interval so e.g. the number of seconds (as a number), you can do something like this:

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;

The result of the above is 55499.5802




回答2:


Read this article: http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129

Example:

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

   SECONDS 
---------- 
   6269539


来源:https://stackoverflow.com/questions/10348140/subtracting-timestamp-in-oracle-returning-weird-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!