Re: return MAX and when it happened

From: Sam Mason <sam(at)samason(dot)me(dot)uk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: return MAX and when it happened
Date: 2008-11-19 15:21:23
Message-ID: 20081119152123.GE2459@frubble.xen.chris-lamb.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Nov 19, 2008 at 08:47:57AM -0600, Scara Maccai wrote:
> CREATE TABLE mytab
> (
> num integer,
> mydate timestamp
> );
>
> and I want to find MAX(num) and the "mydate" where it first happened.
>
> I guess I could use
>
> select * from mytab where num = (select MAX(num) from mytab) order by
> mydate limit 1;

Why not just do:

SELECT * FROM mytab
ORDER BY num, mydate
LIMIT 1;

If you're trying to do more complicated things, DISTINCT ON may be more
useful.

> Do I have to write my own MAX function, something like:
>
> select MYMAX(num, timestamp) from mytab
>
> which would return a custom type? Or is there a better way?

I've wanted MAX to support this sort of thing several times before, but
alas it doesn't.

Sam

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Scara Maccai 2008-11-19 15:35:34 Re: return MAX and when it happened
Previous Message Csaba Nagy 2008-11-19 15:21:05 Re: return MAX and when it happened