kralco626
kralco626

Reputation: 8624

Oracle find average of two timestamps

I don't see hwo this is that ahrd, but I can't seem to find the solution anywhere. It's done for dates, but I can't see to make it work for TIMESTAMP.

I'm trying to do

select avg(last_timestmp - ref_timestmp) as average from param

It keeps telling me it's not a valid number, which I get. But how do I make it a valid number? I have tried extract and a bunch of other stuff but nothing seems to work.

I want the average in seconds. one hundredth of a second would be .01 and 6 hours would be 21600

Thanks!

Upvotes: 7

Views: 17505

Answers (2)

Craig
Craig

Reputation: 5820

You can use EXTRACT to get out the parts as seconds and add them up then calculate your average:

select
    avg(extract(second from intrvl)
        + extract(minute from intrvl) * 60
        + extract(hour from intrvl) * 60 * 60
        + extract(day from intrvl) * 60 * 60 * 24) average
from (
    select (last_timestmp - ref_timestmp) intrvl 
    from param
)

Upvotes: 6

Johan
Johan

Reputation: 76537

You might try

SELECT AVG(p.last_date - p.ref_date) as average FROM (
  SELECT 
    last_timestamp - TO_DATE('1970-01-01', 'YYYY-MM-DD') \* 8640000 as last_date
    ,ref_timestamp - TO_DATE('1970-01-01', 'YYYY-MM-DD') \* 8640000 as ref_date
  FROM param ) p

This will give you the difference in milliseconds.

See: http://blogs.oracle.com/mock/entry/converting_oracle_dates_to_unix

Upvotes: 2

Related Questions