From: | Robert James <srobertjames(at)gmail(dot)com> |
---|---|
To: | Jack Christensen <jack(at)jackchristensen(dot)com> |
Cc: | pgsql-general(at)postgresql(dot)org |
Subject: | Re: Picking the first of an order in an aggregate query |
Date: | 2012-12-31 20:38:01 |
Message-ID: | CAGYyBggqBX0oSuRcV_7cNZTe11Noi+hojqxdTtAZHKEFHTJPxQ@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
DISTINCT is a very simple solution!
But I have one problem: In addition to the FIRST fields, I also do
want some aggregate functions. More accurately, it would be:
SELECT grouping_field, FIRST(field_a), FIRST(field_b), SUM(field_x),
MAX(field_y)
...
How should I do that? Should I do two queries with a join on the
grouping field? Or is there a more direct way?
On 12/31/12, Jack Christensen <jack(at)jackchristensen(dot)com> wrote:
> 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/
>
>
>
> --
> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>
From | Date | Subject | |
---|---|---|---|
Next Message | François Beausoleil | 2012-12-31 21:03:01 | Re: Picking the first of an order in an aggregate query |
Previous Message | Philipp Kraus | 2012-12-31 19:15:36 | trigger on adding / deleting / modify user on pg_authid |