From: redhog <redhog@redhog.org>
To: pgsql-general@postgresql.org
Subject: Re: help with a query
Date: 5 Nov 2006 16:11:10 -0800
Message-ID: <1162771870.067202.282060@b28g2000cwb.googlegroups.com> (raw)
In-Reply-To: <004b01c6ff86$bc254ee0$23d6bed5@oem41cbbf9e178>
References: <004b01c6ff86$bc254ee0$23d6bed5@oem41cbbf9e178>
If you do not want to amend your table with extra information, this is
how you do it:
Suppose you have a table
create table events (
time timestamp,
object int refers objects(id), -- The thing that had its ignition
turned on or off at this time
ignition boolean,
comment varchar
);
You can then do
select distinct on (e1.time, e1.object, e1.comment)
e1.time as start,
e2.time as end,
e2.time - e1.time as duration,
e1.object,
e1.comment
from
events as e1,
events as e2
where
e1.object = e2.object
and e1.time < e2.time
order by
e1.time, e1.object, e1.comment, e2.time asc;
The trick here is to sort by e2.time in ascending order, and to not
include e2.time (or any of e2:s fields) in the distinct condition.
This causes all rows where the values from e1 are the same to be
considered duplicates, and only the first one of them included in the
result - which is the one with the lowest e2.time value, since we did
sort on that key in ascending order.
Note that this trick works since order by is processed before the
distinct clause. This is specifically noted in the PostgreSQL manual.
Note that there is a slightly more "intuitive" way of doing this using
a subquery with a min() aggregate function, but this is considerably
less efficient, especially with larger tables (use "explain" and you'll
understund why).
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: redhog@redhog.org
Subject: Re: help with a query
In-Reply-To: <1162771870.067202.282060@b28g2000cwb.googlegroups.com>
References: <004b01c6ff86$bc254ee0$23d6bed5@oem41cbbf9e178> <1162771870.067202.282060@b28g2000cwb.googlegroups.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox