Skip site navigation (1) Skip section navigation (2)

Peripheral Links

Header And Logo

PostgreSQL
| The world's most advanced open source database.

Site Navigation

Search for
  Advanced Search

Re: Ordering of records in group by not possible


  • From: Chris Kratz <chris(dot)kratz(at)vistashare(dot)com>
  • To: Ludwig Isaac Lim <ludz_lim(at)yahoo(dot)com>
  • Cc: pgsql-general(at)postgresql(dot)org
  • Subject: Re: Ordering of records in group by not possible
  • Date: Wed, 26 Apr 2006 11:30:51 -0400
  • Message-id: <200604261130(dot)51975(dot)chris(dot)kratz(at)vistashare(dot)com>

On Wednesday 26 April 2006 11:19 am, Ludwig Isaac Lim wrote:
> Hi:
> > You could order by "column 2" if you want to order on the
> > results on
> > your aggregate:
> > 	Select a, aggregate(b)
> > 	from c
> > 	group by a
> > 	order by a,2
>
> another alternative is :
>
>    select a , aggregrate(b) as <alias>
>    from c
>    group by a
>    order by a, <alias>
>
> e.g.
>
>    select a,sum(b) as sum_b
>    from c
>    group by a
>    order by a, sum_b
>
> ludwig lim
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
> ---------------------------(end of broadcast)---------------------------
> TIP 6: explain analyze is your friend

Ironically, before we realized we weren't getting the results we expected, we 
were doing something like this.

select a,aggregate(b) as b
from c
group by a
order by a,b

We got lucky the first couple of tests and it appeared to work.  It was only 
later that we realized that the sort was actually sorting the aggregated 
values after the group by, not the rows going into the order sensitive 
aggregate as we had hoped.

I actually like the fact that the sort is the last thing that is done on a 
query, in most cases this is what makes sense.  It's just frustrating in this 
one place to have little control of the records going into the grouping code 
since the aggregates we are using are order sensitive.  Think functions like 
first and last.

-Chris
-- 
Chris Kratz



Home | Main Index | Thread Index

Privacy Policy | PostgreSQL Archives hosted by Command Prompt, Inc. | Designed by tinysofa
Copyright © 1996 – 2008 PostgreSQL Global Development Group