gpt4 book ai didi

SQL 从时间戳差异中提取值

转载 作者:行者123 更新时间:2023-12-04 18:25:07 24 4
gpt4 key购买 nike

我正在尝试从减去 Oracle 数据库中的两个时间戳的输出中提取天、小时、分钟、秒。然后我想获取提取的值并将它们放入单独的列中。我可以使用 substr 完成此操作,但这似乎效率不高。是否有更有效和程序化的方式来提取值?以下是具有当前和所需输出的示例查询。

示例:

SELECT 

to_timestamp('2019-11-10 15:00:00', 'YYYY-MM-DD hh24:mi:ss') -
to_timestamp('2019-10-25 13:25:00', 'YYYY-MM-DD hh24:mi:ss')
as TIME_DIFF,

SUBSTR(to_timestamp('2019-11-10 15:00:00', 'YYYY-MM-DD hh24:mi:ss') -
to_timestamp('2019-10-25 13:25:00', 'YYYY-MM-DD hh24:mi:ss'), 9, 2)
as DAYS

from dual

当前输出:

TIME_DIFF                     | DAYS
------------------------------+-----
+000000016 01:35:00.000000000 | 16

期望的输出:

DAYS | HOUR | MIN | SS
-----+------+-----+---+
16 | 01 | 35 | 00

最佳答案

您可以使用 extract() 从区间中提取所需的值:

with t as (
select to_timestamp('2019-11-10 15:00:00', 'YYYY-MM-DD hh24:mi:ss') -
to_timestamp('2019-10-25 13:25:00', 'YYYY-MM-DD hh24:mi:ss')
as TIME_DIFF
from dual
)
select
extract(day from time_diff) days,
extract(hour from time_diff) hours,
extract(minute from time_diff) minutes,
extract(second from time_diff) seconds
from t

Demo on DB Fiddle :

DAYS | HOURS | MINUTES | SECONDS---: | ----: | ------: | ------:  16 |     1 |      35 |       0

关于SQL 从时间戳差异中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com