X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 43A1F11F68D5 for ; Wed, 29 Mar 2006 19:52:33 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 60708-06 for ; Wed, 29 Mar 2006 19:52:32 -0400 (AST) Received: from svr4.postgresql.org (svr4.postgresql.org [66.98.251.159]) by postgresql.org (Postfix) with ESMTP id CD77911F68D4 for ; Wed, 29 Mar 2006 19:52:30 -0400 (AST) Received: from alimail.net (potatis.alimail.net [84.19.131.11]) by svr4.postgresql.org (Postfix) with ESMTP id 479525AF068 for ; Wed, 29 Mar 2006 23:52:30 +0000 (GMT) Received: from [192.168.1.10] ([84.19.128.181]) by alimail.net (alimail.net [10.1.8.71]) (MDaemon.PRO.v8.0.4.R) with ESMTP id md50000569788.msg for ; Thu, 30 Mar 2006 01:49:39 +0200 Mime-Version: 1.0 (Apple Message framework v746.3) In-Reply-To: References: Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed Message-Id: <5047BA59-331B-4F6B-AF2C-9C9210E3CAE0@tele2.se> Content-Transfer-Encoding: 7bit From: Niklas Johansson Subject: Re: Ugly group by problem Date: Thu, 30 Mar 2006 01:49:18 +0200 To: pgsql-sql@postgresql.org X-Mailer: Apple Mail (2.746.3) X-Spam-Processed: alimail.net, Thu, 30 Mar 2006 01:49:39 +0200 (not processed: message from trusted or authenticated source) X-MDRemoteIP: 84.19.128.181 X-Return-Path: spot@tele2.se X-MDaemon-Deliver-To: pgsql-sql@postgresql.org Reply-To: spot@tele2.se X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.449 required=5 tests=[AWL=-0.030, DNS_FROM_RFC_ABUSE=0.479, UPPERCASE_25_50=0] X-Spam-Score: 0.449 X-Spam-Level: X-Archive-Number: 200603/456 X-Sequence-Number: 24802 On 29 mar 2006, at 17.42, Achilleus Mantzios wrote: > The _int_union trick is to force the arrays to have unique values. > The order by has the meaning that '{5,23}' and '{23,5}' should be > treated > the same way. I didn't have the _int_union function. Is it internal? What PG- version did you use? I solved it using DISTINCT instead (perhaps making it a little simpler as well): SELECT ARRAY(SELECT DISTINCT feat_id FROM linktest WHERE link_id=t1.link_id ORDER BY feat_id) AS feat_group, SUM(other) FROM linktext t1 GROUP BY 1; feat_group | sum -----------+----- {2} | 1 {5,23} | 13 {23} | 14 (3 rows) Of course I haven't tested the performance on a table containing a lot of data... I'm not sure how the planner will treat the ARRAY- construct. You might be able to speed it up by turning it into a function marked STABLE, something like this: CREATE OR REPLACE FUNCTION feat_group(INTEGER) RETURNS INTEGER[] AS $$ SELECT ARRAY(SELECT DISTINCT feat_id FROM linktest WHERE link_id=$1 ORDER BY feat_id); $$ LANGUAGE sql STABLE; SELECT feat_group(link_id), SUM(other) FROM linktext t1 GROUP BY 1; Sincerely, Niklas Johansson