简体   繁体   English

在ORACLE SQL中使用带小数的替代

[英]Substraction with decimal in ORACLE SQL

I need to substract 2 timestamps in the given format: 我需要以给定的格式减去2个时间戳:

16/01/17 07:01:06,165000000 
16/01/17 07:01:06,244000000

I want to express the result with 2 decimal values but somewhere in the CAST process I am loosing precision. 我想用2个十进制值表示结果,但在CAST过程中的某个地方,我正在失去精度。 My atempt by now goes this way: 我现在的尝试是这样的:

select 
  id,
  trunc((CAST(MAX(T.TIMESTAMP) AS DATE) - CAST(MIN(T.TIMESTAMP) AS DATE))*24*60*60,2) as result 
from table T
group by id;

But I get id_1 '0' as a result for the two timestamps above even after I set the truncate decimals at 2. 但是,即使我将截断小数设置为2,我的上述两个时间戳也会得到id_1 '0'

Is there a way that I can obtain the 0.XX aa a result of the substraction? 有没有办法可以获得0.XX aa减法的结果?

It's because you are casting the timestamp to date. 这是因为你正在投射时间戳到目前为止。

Use to_timestamp to convert your string into timestamp. 使用to_timestamp将字符串转换为时间戳。

Try this: 尝试这个:

with your_table(tstamp) as (
  select '16/01/17 07:01:06,165000000' from dual union all
  select '16/01/17 07:01:06,244000000' from dual
),
your_table_casted as (
    select to_timestamp(tstamp,'dd/mm/yy hh24:mi:ss,ff') tstamp from your_table
)
select trunc(sysdate + (max(tstamp) - min(tstamp)) * 86400 - sysdate, 2) diff 
from your_table_casted;

The difference between two timestamps is INTERVAL DAY TO SECOND . 两个时间戳之间的差异是INTERVAL DAY TO SECOND

To convert it into seconds, use the above trick. 要将其转换为秒,请使用上述技巧。

DATE—This datatype stores a date and a time, resolved to the second. DATE-此数据类型存储日期和时间,解析为秒。 It does not include the time zone. 它不包括时区。 DATE is the oldest and most commonly used datatype for working with dates in Oracle applications. DATE是在Oracle应用程序中处理日期的最早且最常用的数据类型。

TIMESTAMP—Time stamps are similar to dates, but with these two key distinctions: you can store and manipulate times resolved to the nearest billionth of a second (9 decimal places of precision), and you can associate a time zone with a time stamp, and Oracle Database will take that time zone into account when manipulating the time stamp. TIMESTAMP-时间戳类似于日期,但有两个关键的区别:您可以存储和操作解析的时间到最接近的十亿分之一秒(精度为9位小数),并且您可以将时区与时间戳关联,和Oracle数据库在操作时间戳时会考虑该时区。

The result of a substraction of two timestamps is an INTERVAL: 减去两个时间戳的结果是INTERVAL:

INTERVAL—Whereas DATE and TIMESTAMP record a specific point in time, INTERVAL records and computes a time duration. INTERVAL - DATE和TIMESTAMP记录特定时间点,INTERVAL记录并计算持续时间。 You can specify an interval in terms of years and months, or days and seconds. 您可以按年和月,或天和秒指定间隔。

You can find more information here 您可以在此处找到更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM