如何计算同一列中时间戳之间的时差

时间:2018-02-19 19:06:44

标签: sql oracle

我有一个oracle数据库,机器人正在处理索赔。我有机器人ID,声明ID和进程时间戳。我需要计算机器人从一个声明到下一个声明的时间。然后,我需要显示声明之间超过5分钟的机器人,以及开始声明的声明ID。举个例子:

Bot ID     Claim ID       Process Timestamp
123        12345          2/19/2018 12:45:26
123        12346          2/19/2018 12:55:11

机器人花了超过5分钟处理索赔12345所以我需要显示:

Bot ID     Claim ID       Minutes
123         12345         9:85

1 个答案:

答案 0 :(得分:2)

您可以使用lag()的分析形式查看机器人ID的上一行,您可以在其中将window子句中的“previous”定义为基于时间戳。所以:

select bot_id, claim_id,
  process_timestamp - lag(process_timestamp)
    over (partition by bot_id order by process_timestamp) as elapsed
from your_table;

    BOT_ID   CLAIM_ID ELAPSED             
---------- ---------- --------------------
       123      12345                     
       123      12346 +00 00:09:45.000000 

从另一个时间戳中减去一个时间戳会给你一个间隔,你不能直接格式化,但你可以提取它的元素并将它们作为一个字符串粘在一起:

select bot_id, claim_id,
  extract(minute from elapsed) || ':' || extract(second from elapsed) as minutes
from (
  select bot_id, claim_id,
    process_timestamp - lag(process_timestamp)
      over (partition by bot_id order by process_timestamp) as elapsed
  from your_table
)
where elapsed > interval '5' minute;

    BOT_ID   CLAIM_ID MINUTES   
---------- ---------- ----------
       123      12346 9:45      

或者如果索赔可能超过一小时:

select bot_id, claim_id,
  (60 * extract(hour from elapsed)) + extract(minute from elapsed)
    || ':' || extract(second from elapsed) as minutes
from (
...

如果列实际上是日期而不是时间戳,则减法给出数字而不是间隔。将其转换为字符串只需将一天中的一小部分添加到午夜的名义日期即可:

select bot_id, claim_id, to_char(date '1900-01-01' + elapsed, 'MI:SS') as minutes
from (
  select bot_id, claim_id,
    process_timestamp - lag(process_timestamp)
      over (partition by bot_id order by process_timestamp) as elapsed
  from your_table
)
where elapsed > 5/1440;

    BOT_ID   CLAIM_ID MINUTES   
---------- ---------- ----------
       123      12346 09:45     

如果可能超过一小时,则可以制作格式模型HH24:MI:SS。 (从多个小时算起的分钟数,比如120分钟,稍微复杂一些。)

过滤器现在是5/1440 - 一天有1440分钟,因此代表五分钟。

相关问题