views:

1477

answers:

1

I need to select an entity that is valid at the midth of the validity of different entity.

As a simplified example, I want to do something like this:

select 
    * 
from
    o1, o2
where
    o1.from < (o2.to - ((o2.to - o2.from) /2) )
    and
    o1.to > (o2.to - ((o2.to - o2.from) /2) )

How can I compute "(o2.to - ((o2.to - o2.from) /2) )" in SQL, assuming that to and from are timestamps?

+2  A: 

Did you try what you have written? It looks like it should work to me:

(o2.to - o2.from)

This will give you a partial day difference, eg:

  1  select (trunc(sysdate) - trunc(sysdate+1))/2 from dual
  2*
SQL> /

(TRUNC(SYSDATE)-TRUNC(SYSDATE+1))/2
-----------------------------------
                                -.5

SQL>

Then if you add that result to the original date, you will get the date and time at the midpoint:

SQL> select to_char(a.d, 'YYYY-MON-DD HH24:MI')
  2  from
  3  (  select trunc(sysdate) + (trunc(sysdate+1) - trunc(sysdate))/2 d from dual
  4  ) a;

TO_CHAR(A.D,'YYYY
-----------------
2009-MAY-13 12:00
Stephen ODonnell