如何比较两个日期之间的秒数与oracle中的整数

tkclm6bt  于 2023-03-29  发布在  Oracle
关注(0)|答案(1)|浏览(162)

我想把两个日期之间的秒数与一个整数进行比较,但结果不是预期的。

WITH m AS (
 SELECT to_date('2023-03-01 12:00:00','yyyy-mm-dd hh24:mi:ss') in_time,
        to_date('2023-03-01 12:00:30','yyyy-mm-dd hh24:mi:ss') out_time
 FROM dual
)

SELECT
(out_time-in_time)*24*60*60 delta_seconds,
(CASE WHEN (out_time-in_time)*24*60*60=30 THEN 'equal' else 'not equal' end) flag
FROM m

结果是

delta_seconds | flag
  30          | not equal

我以为结果是

delta_seconds | flag
  30          | equal

为什么?

f2uvfpb9

f2uvfpb91#

两个日期相减得到的结果是某个天数的分数,然后乘以86400得到秒。分数并不精确:

WITH m AS (
 SELECT to_date('2023-03-01 12:00:00','yyyy-mm-dd hh24:mi:ss') in_time,
        to_date('2023-03-01 12:00:30','yyyy-mm-dd hh24:mi:ss') out_time
 FROM dual
)

SELECT
(out_time-in_time)*24*60*60 delta_seconds,
(CASE WHEN (out_time-in_time)*24*60*60=30 THEN 'equal' else 'not equal' end) flag
FROM m
Δ_秒旗帜
29.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999不等

您的客户端正在对数字进行四舍五入以进行显示。如果您使用set numwidth 41或更高版本,则可以在SQL*Plus或SQL Developer中看到相同的输出,这将为所有这些数字、小数点和可能显示的减号提供足够的空间;对于像默认值10这样的较小值,它必须隐式地舍入以能够显示结果。
要获得您想要的结果,需要手动舍入数字:

WITH m AS (
 SELECT to_date('2023-03-01 12:00:00','yyyy-mm-dd hh24:mi:ss') in_time,
        to_date('2023-03-01 12:00:30','yyyy-mm-dd hh24:mi:ss') out_time
 FROM dual
)

SELECT
round((out_time-in_time)*24*60*60) delta_seconds,
CASE WHEN round((out_time-in_time)*24*60*60)=30 THEN 'equal' else 'not equal' end flag
FROM m
Δ_秒旗帜
三十相等

fiddle
如果必须先将日期转换为时间戳或将日期相减转换为时间间隔,则还可以将差值作为时间间隔获取;然后你可以将其与interval文字进行比较:

SELECT
extract(second from (cast(out_time as timestamp) - cast(in_time as timestamp))) delta_seconds,
CASE WHEN extract(second from (cast(out_time as timestamp) - cast(in_time as timestamp)))=30 THEN 'equal' else 'not equal' end flag
FROM m
Δ_秒旗帜
三十相等
SELECT
cast(out_time as timestamp) - cast(in_time as timestamp) delta_interval,
CASE WHEN cast(out_time as timestamp) - cast(in_time as timestamp) = interval '30' second THEN 'equal' else 'not equal' end flag
FROM m
Δ间期旗帜
0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000相等
SELECT
(out_time-in_time)*24*60*60 * interval '1' second delta_interval,
CASE WHEN (out_time-in_time)*24*60*60 * interval '1' second = interval '30' second THEN 'equal' else 'not equal' end flag
FROM m
Δ间期旗帜
000000000 00:00:30.000000000相等

fiddle

相关问题