Re: Find overlapping time intervals, how?

From: Alvaro Herrera Munoz <alvherre(at)dcc(dot)uchile(dot)cl>
To: Holger Marzen <holger(at)marzen(dot)de>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Find overlapping time intervals, how?
Date: 2003-09-10 00:17:30
Message-ID: 20030910001730.GD22244@dcc.uchile.cl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, Sep 09, 2003 at 09:29:58PM +0200, Holger Marzen wrote:
> Say, we have uptimes from several servers:
>
> Server up_from up_to
> ------ ------- -------
> s1 0:00 8:00
> s1 10:00 20:00
> s1 22:00 24:00 (would better be a timestamp with 0:00 and next day)
> s2 0:00 4:00
> s2 6:00 23:00

You better get a timestamp field for the up_from and up_to, because it's
going to be very difficult to deal with only times (unless you want
a report of a single day).

I've done a similar thing with something like:

select
max(s1_uptime.up_from, s2_uptime.up_from) as start,
min(s1_uptime.up_to, s2_uptime.up_to) as end
from (select up_from, up_to from table where server=s1) as s1_uptime,
(select up_from, up_to from table where server=s2) as s2_uptime
where (s1_uptime.up_from, s1_uptime.up_to) overlaps
(s2_uptime.up_from, s2_uptime.up_to)

I'm not sure if the OVERLAPS operator works on released versions; I've
only used it on 7.4, and even there it was undocumented until yesterday
(I found it peeking at the source looking for something else).

You also have to build max(timestamp, timestamp) and min(timestamp,
timestamp) functions:

create function max(timestamp, timestamp) returns timestamp as
'select case if $1 > $2 then $1 else $2' language sql;

(see here for OVERLAPS:
http://developer.postgresql.org/docs/postgres/functions-datetime.html )

--
Alvaro Herrera (<alvherre[(at)]dcc(dot)uchile(dot)cl>)
www.google.com: interfaz de linea de comando para la web.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message --CELKO-- 2003-09-10 01:18:39 Re: Find overlapping time intervals, how?
Previous Message Kathy Zhu 2003-09-10 00:13:13 Re: encoding again