Oracle时间戳差异

时间:2015-02-02 21:44:58

标签: sql oracle timestamp

我有一个DB表(Oracle),如下所示:

ID             STATUS             TIMESTAMP
--             ------             ---------
1              NEW                30-JAN-15 08.11.11.803384000 PM
2              NEW                30-JAN-15 08.11.13.606681000 PM 
1              COMPLETED          30-JAN-15 08.11.15.997794000 PM
2              COMPLETED          30-JAN-15 08.11.16.469299000 PM

我想实现两件事:

  1. 从状态新到完成的每个ID的时间戳差异
  2. 新到完成之间的所有ID之间的平均时间
  3. 有没有更好的方法来实现这一目标?

3 个答案:

答案 0 :(得分:0)

如果每个id只有两行,而“new”在“完成”之前,那么你可以这样做以获得每个id的差异:

select id, max(timestamp) - min(timestamp)
from dbtable t
group by id;

或获取平均值的相关查询:

select avg(diff)
from (select id, max(timestamp) - min(timestamp) as diff
      from dbtable t
      group by id
     ) t;

差异以天和小数部分来衡量。

答案 1 :(得分:0)

这应该让你开始:

SELECT ID
, ( TO_TIMESTAMP(NEWTS, 'DD-Mon-RR HH:MI:SS.FF AM') - TO_TIMESTAMP(COMTS, 'DD-Mon-RR HH:MI:SS.FF AM')) DIFF
FROM (select 
MIN(case when status='NEW'
 THEN TIMESTAMP
end) NEWTS,
MIN(case when status='COMPLETED'
 THEN TIMESTAMP
end) COMTS
, ID
FROM Table1
GROUP BY ID) A

然后,您可以对此查询执行AVG以获得第二个答案

答案 2 :(得分:0)

这会以分钟为单位返回差异。

p.s : not tested


SELECT N.ID,
(24*60)*(C.TIMESTAMP - N.TIMESTAMP) AS DIFF_IN_MINUTES
FROM
(SELECT ID, TIMESTAMP
    FROM TABLE_NAME
    WHERE STATUS = 'NEW'
)N
INNER JOIN
(SELECT ID, TIMESTAMP
    FROM TABLE_NAME
    WHERE STATUS = 'COMPLETED'
)C
ON N.ID = C.ID