Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id ECEDD632BBB for ; Tue, 10 Aug 2010 12:57:05 -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 97343-04 for ; Tue, 10 Aug 2010 15:56:58 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id B3667632B89 for ; Tue, 10 Aug 2010 12:56:58 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1OirCB-0005uh-G8 for pgsql-performance@postgresql.org; Tue, 10 Aug 2010 17:56:55 +0200 Received: from ppp-188-174-22-224.dynamic.mnet-online.de ([188.174.22.224]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 10 Aug 2010 17:56:55 +0200 Received: from spam_eater by ppp-188-174-22-224.dynamic.mnet-online.de with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 10 Aug 2010 17:56:55 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-performance@postgresql.org From: Thomas Kellerer Subject: Re: Sorted group by Date: Tue, 10 Aug 2010 17:56:46 +0200 Lines: 20 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: ppp-188-174-22-224.dynamic.mnet-online.de User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.21) Gecko/20090302 Thunderbird/2.0.0.21 Mnenhy/0.7.5.666 In-Reply-To: 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/104 X-Sequence-Number: 39947 Matthew Wakeling wrote on 10.08.2010 17:40: > 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? No. It's built in (8.4) and it's called Windowing functions: http://www.postgresql.org/docs/8.4/static/tutorial-window.html http://www.postgresql.org/docs/8.4/static/functions-window.html SELECT group, last_value(value) over(ORDER BY number) FROM table You don't need the group by then (but you can apply e.g. an ORDER BY GROUP) Thomas