Re: MSAccess-like Last() with sorting before grouping

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: Octavio Alvarez <alvarezp(at)octavio(dot)ods(dot)org>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: MSAccess-like Last() with sorting before grouping
Date: 2003-05-16 17:36:24
Message-ID: 20030516173624.GA23168@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

On Wed, May 14, 2003 at 17:50:04 -0700,
Octavio Alvarez <alvarezp(at)octavio(dot)ods(dot)org> wrote:
>
> I need it to have the following output:
>
> id | group_key | sort_key | data
> ----+-----------+----------+------
> 4 | 1 | 9 | 2
> 7 | 2 | 7 | 3
> 8 | 3 | 6 | 5
>
> Which is, selecting the top value from sort_key from each different set of
> group_key. I can't program a last() function because it wouldn't work for
> group_key=3 in the example. ORDER BY always sorts the results after the
> grouping. I tried min/max functions but they apply to each column
> individually.
>
> Is there any way I can ask for this info to the SQL server?

If you are willing to use nonstandard sql, distinct on should do what you
want. Something like:

select distinct on (group_key) id, group_key, sort_key, data from table_name
order by sort_key desc;

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Juliet May 2003-05-16 17:46:28 Re: Problems with join (no such attribute, but it exists)
Previous Message Joe Conway 2003-05-16 16:48:06 Re: SELECT across multiple db