X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 9D0EE54D3A for ; Thu, 24 Feb 2005 15:32:22 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 63766-10 for ; Thu, 24 Feb 2005 15:32:13 +0000 (GMT) Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by svr1.postgresql.org (Postfix) with ESMTP id C2563531C7 for ; Thu, 24 Feb 2005 15:32:12 +0000 (GMT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.1/8.13.1) with ESMTP id j1OFWGRU025017; Thu, 24 Feb 2005 10:32:16 -0500 (EST) To: Richard Huxton Cc: Kai Hessing , pgsql-sql@postgresql.org Subject: Re: Advanced SELECT In-reply-to: <421D8EA6.7020107@archonet.com> References: <383fk1F5hq3hhU1@individual.net> <421D8EA6.7020107@archonet.com> Comments: In-reply-to Richard Huxton message dated "Thu, 24 Feb 2005 08:21:58 +0000" Date: Thu, 24 Feb 2005 10:32:16 -0500 Message-ID: <25016.1109259136@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.007 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200502/306 X-Sequence-Number: 20416 Richard Huxton writes: > Search the mailing-list archives for "custom aggregate concat" and > you'll quickly find an example of how to write your own custom aggregate > (like SUM()). > Warning - I don't think you can guarantee the order of elements in the > aggregated sectors. In recent PG versions you can. For example, select key1, custom_aggregate(detail_field) from (select key1, detail_field from my_table order by key1, key2) ss group by key1 order by key1; The detail_field values will be fed to the aggregate in order by key2 within each key1 group. This is one of the examples that motivated allowing ORDER BY in subselects, even though it's outside the SQL spec. [ experiments... ] This works reliably in 7.4 and up. Before that, the optimizer didn't make the connection between the sort ordering of the inner query and that needed by the outer, so it would repeat the sort step using only key1 and very possibly destroy the key2 ordering. regards, tom lane