Re: Aggregates, group, and order by - Mailing list pgsql-general

From Tom Lane
Subject Re: Aggregates, group, and order by
Date
Msg-id 18118.1131373448@sss.pgh.pa.us
Whole thread Raw
In response to Re: Aggregates, group, and order by  (Joe Conway <mail@joeconway.com>)
Responses Re: Aggregates, group, and order by  (Michael Glaesemann <grzm@myrealbox.com>)
List pgsql-general
Joe Conway <mail@joeconway.com> writes:
> Michael Glaesemann wrote:
>> I'm trying to concatenate strings in variable orders using a custom
>> aggregate.

> Just use a subselect --  you're looking for this, correct?

> regression=# select bar_id, array_accum(foo_value) from (select * from
> ordered_foo order by foo_pos) as ss group by bar_id order by bar_id;

Strictly speaking, you need this:

    select bar_id, array_accum(foo_value) from
    (select * from ordered_foo order by bar_id, foo_pos) as ss
    group by bar_id order by bar_id;

ie, sort the subselect by the grouping key of the outer query, then
by the thing that should control the aggregation order within groups.

The way Joe shows will work only if the planner chooses to use a hash
aggregate plan.  If it chooses a sort/uniq aggregation plan, the re-sort
will destroy the sort order of the sub-select's output.

            regards, tom lane

pgsql-general by date:

Previous
From: Guido Neitzer
Date:
Subject: Re: PostgreSQL, UTF-8 and Mac OS X
Next
From: Michael Glaesemann
Date:
Subject: Re: Aggregates, group, and order by