pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: hubert depesz lubaczewski <depesz@depesz.com>
To: Matthew Wakeling <matthew@flymine.org>
Cc: pgsql-performance@postgresql.org
Subject: Re: Sorted group by
Date: Tue, 10 Aug 2010 18:11:07 +0200
Message-ID: <20100810161107.GA9680@depesz.com> (raw)
In-Reply-To: <alpine.DEB.2.00.1008101627440.2654@aragorn.flymine.org>
References: <alpine.DEB.2.00.1008101627440.2654@aragorn.flymine.org>

On Tue, Aug 10, 2010 at 04:40:16PM +0100, Matthew Wakeling wrote:
> 
> I'm trying to eke a little bit more performance out of an
> application, and I was wondering if there was a better way to do the
> following:
> 
> I am trying to retrieve, for many sets of rows grouped on a couple
> of fields, the value of an ungrouped field where the row has the
> highest value in another ungrouped field. For instance, I have the
> following table setup:
> 
> group  | whatever type
> value  | whatever type
> number | int
> Index: group
> 
> I then have rows like this:
> 
> group     | value         | number
> -------------------------------------
> Foo       | foo           | 1
> Foo       | turnips       | 2
> Bar       | albatross     | 3
> Bar       | monkey        | 4
> 
> I want to receive results like this:
> 
> group     | value
> -----------------------
> Foo       | turnips
> Bar       | monkey
> 
> Currently, I do this in my application by ordering by the number and
> only using the last value. I imagine that this is something that can
> be done in the new Postgres 9, with a sorted group by - something
> like this:
> 
> SELECT group, LAST(value, ORDER BY number) FROM table GROUP BY group
> 
> Is this something that is already built in, or would I have to write
> my own LAST aggregate function?

this is trivially done when usign 'distinct on':
select distinct on (group) *
from table
order by group desc, number desc;

depesz

-- 
Linkedin: http://www.linkedin.com/in/depesz  /  blog: http://www.depesz.com/
jid/gtalk: depesz@depesz.com / aim:depeszhdl / skype:depesz_hdl / gg:6749007



view thread (11+ messages)  latest in thread

Message-ID: <20100810161107.GA9680@depesz.com>
Permalink:  ../20100810161107.GA9680@depesz.com/
Also on:    postgresql.org/message-id/20100810161107.GA9680@depesz.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: depesz@depesz.com, matthew@flymine.org
  Subject: Re: Sorted group by
  In-Reply-To: <20100810161107.GA9680@depesz.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox