Re: Aggregates, group, and order by

From: Michael Glaesemann <grzm(at)myrealbox(dot)com>
To: Roger Hand <RHand(at)kailea(dot)com>, Joe Conway <mail(at)joeconway(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Aggregates, group, and order by
Date: 2005-11-07 10:15:09
Message-ID: 15CCEF9B-1C4F-47BF-A306-F9E991615F68@myrealbox.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Nov 7, 2005, at 17:40 , Roger Hand wrote:

> On Monday, November 07, 2005 12:12 AM
> Michael Glaesemann wrote:
>>
>> select bar_id, array_accum(foo_value)
>> from ordered_foo
>> group by bar_id
>> order by bar_id;
>> bar_id | array_accum
>> --------+-----------------------------
>> 1 | {delta,alpha,charlie,bravo}
>> 2 | {C,B,A,D}
>>
>>
>> The result I'd like to see is
>> bar_id | array_accum
>> --------+-----------------------------
>> 1 | {alpha,bravo,charlie,delta}
>> 2 | {A,B,C,D}
>
> select bar_id, array_accum(foo_value)
> from
> (SELECT * FROM ordered_foo ORDER BY foo_pos) foo
> group by bar_id
> order by bar_id;
>
> bar_id,array_accum
> 1,{alpha,bravo,charlie,delta}
> 2,{A,B,C,D}

On Nov 7, 2005, at 18:09 , Joe Conway wrote:
>
> 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;
> bar_id | array_accum
> --------+-----------------------------
> 1 | {alpha,bravo,charlie,delta}
> 2 | {A,B,C,D}
> (2 rows)

That is very sweet. Is the subquery guaranteed to retain the order?
My understanding is that a table is not necessarily ordered, so the
result of a subquery isn't necessarily going to be ordered either.

I'm having a bit of trouble getting this to work with the non-reduced
case: the array_accum results aren't always ordered as I want. Going
to mess around with it a little more to see if I can find out why.

Thanks again!

Michael Glaesemann
grzm myrealbox com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message ctobini 2005-11-07 11:15:21 Recuperate each line of a result into a variable ?
Previous Message Mariusz Czułada 2005-11-07 09:17:31 Re: Oracle 10g Express - any danger for Postgres?