From: Marc Sherman <msherman@projectile.ca>
To: pgsql-sql List <pgsql-sql@postgresql.org>
Subject: RE: Select most recent record?
Date: Wed, 16 May 2001 10:52:31 -0400
Message-ID: <CGEPKMKAIFJINAOACFFEGEJHCGAA.msherman@projectile.ca> (raw)
In-Reply-To: <17169.990023757@sss.pgh.pa.us>
From: Tom Lane [mailto:tgl@sss.pgh.pa.us]
>
> "Marc Sherman" <msherman@projectile.ca> writes:
> > I'd like to select the newest (max(timestamp)) row for each id,
> > before a given cutoff date; is this possible?
>
> select * from log order by timestamp desc limit 1;
Heh. I obviously simplified my situation too much.
This is closer to what I've really got:
create table user (userid int4 primary key, groupid int4);
create table log (userid int4, timestamp datetime, value int4);
I need to select sum(value) for each group, where the values chosen
are the newest log entry for each group member that is before a cutoff
date (April 1, 2001).
Here's what I'm currently using:
select user.groupid, sum(l1.value)
from log as l1, user
where user.userid=log.userid
and log.timestamp in (
select max(timestamp) from log
where log.timestamp<'2001-04-01'
and log.userid=l1.userid)
group by user.groupid;
When I first posted, this was _very_ slow. I've since improved
it by adding an index on log(userid,timestamp) - now it's just
slow. If anyone knows how to make it faster, I'd appreciate it.
- Marc
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 using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: msherman@projectile.ca
Subject: RE: Select most recent record?
In-Reply-To: <CGEPKMKAIFJINAOACFFEGEJHCGAA.msherman@projectile.ca>
* 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