| From: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> | 
|---|---|
| To: | Andrew Perrin <andrew_perrin(at)unc(dot)edu> | 
| Cc: | Marc Sherman <msherman(at)projectile(dot)ca>, pgsql-sql List <pgsql-sql(at)postgresql(dot)org> | 
| Subject: | Re: Select most recent record? | 
| Date: | 2001-05-16 14:50:17 | 
| Message-ID: | 17280.990024617@sss.pgh.pa.us | 
| Views: | Whole Thread | Raw Message | Download mbox | Resend email | 
| Thread: | |
| Lists: | pgsql-sql | 
Andrew Perrin <andrew_perrin(at)unc(dot)edu> writes:
> Except that he wants max(timestamp) by id; perhaps a GROUP BY would
> help, something like (untested):
Oh, I'm sorry, I missed the "for each id" bit.
> select max(timestamp) from log group by id;
That gives you the max timestamp for each id, all right, but not the
rest of the row in which the max timestamp occurs.  I know of no good
way to get that in standard SQL.  If you don't mind being nonstandard,
this is exactly the problem SELECT DISTINCT ON is meant for:
select distinct on (id) * from log order by id, timestamp desc;
See the SELECT reference page for more about this.
regards, tom lane
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Michael Ansley (UK) | 2001-05-16 14:50:38 | RE: Select most recent record? | 
| Previous Message | Andrew Perrin | 2001-05-16 14:43:22 | Re: Select most recent record? |