Re: Picking the first of an order in an aggregate query - Mailing list pgsql-general

From Jack Christensen
Subject Re: Picking the first of an order in an aggregate query
Date
Msg-id 50E1A49B.3000905@jackchristensen.com
Whole thread Raw
In response to Picking the first of an order in an aggregate query  (Robert James <srobertjames@gmail.com>)
Responses Re: Picking the first of an order in an aggregate query
Re: Picking the first of an order in an aggregate query
List pgsql-general
On 12/31/2012 8:33 AM, Robert James wrote:
> I have a query
>
>    SELECT grouping_field, MIN(field_a), MIN(field_b)
>    FROM ...
>    GROUP BY grouping_field
>
> But, instead of picking the MIN field_a and MIN field_b, I'd like to
> pick field_a and field_b from the first record, according to an order
> I'll specify.  In pseudo-SQL, it would be something like this:
>
>    SELECT grouping_field, FIRST(field_a), FIRST(field_b)
>    FROM ...
>    ORDER BY field_c DESC, field_d ASC, myfunc(field_e) ASC
>    GROUP BY grouping_field
>
> How can I do that with Postgres?
>
>
select distinct on (grouping_field), field_a, field_b
from ...
order by grouping_field, field_a asc, field_b asc


http://www.postgresql.org/docs/9.2/static/sql-select.html#SQL-DISTINCT

--
Jack Christensen
http://jackchristensen.com/



pgsql-general by date:

Previous
From: Robert James
Date:
Subject: Picking the first of an order in an aggregate query
Next
From: Adrian Klaver
Date:
Subject: Re: rights for schema