Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 33A7A632EFC for ; Tue, 10 Aug 2010 13:11:17 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 03910-05 for ; Tue, 10 Aug 2010 16:11:09 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from depesz.com (martin.depesz.com [188.40.39.14]) by mail.postgresql.org (Postfix) with ESMTP id CD2BF632E81 for ; Tue, 10 Aug 2010 13:11:09 -0300 (ADT) Received: from martin.depesz.com ([188.40.39.14] helo=depesz.com) by depesz.com with esmtpa (Exim 4.69) (envelope-from ) id 1OirPv-00036I-7L; Tue, 10 Aug 2010 18:11:07 +0200 Date: Tue, 10 Aug 2010 18:11:07 +0200 From: hubert depesz lubaczewski To: Matthew Wakeling Cc: pgsql-performance@postgresql.org Subject: Re: Sorted group by Message-ID: <20100810161107.GA9680@depesz.com> Reply-To: depesz@depesz.com References: MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.20 (2009-06-14) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201008/107 X-Sequence-Number: 39950 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