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 276D78BA175 for ; Fri, 11 Feb 2005 20:44:17 +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 27823-07 for ; Fri, 11 Feb 2005 20:44:04 +0000 (GMT) Received: from server.bluefire-systems.co.uk (ns.bluefire-systems.co.uk [217.199.164.113]) by svr1.postgresql.org (Postfix) with ESMTP id 21ECE8BA15C for ; Fri, 11 Feb 2005 20:44:04 +0000 (GMT) Received: from [213.78.152.15] (helo=Aurora) by server.bluefire-systems.co.uk with esmtp (Exim 4.42) id 1CzhjC-0001Mo-Uz for pgsql-sql@postgresql.org; Fri, 11 Feb 2005 20:49:27 +0000 From: "Simon Kinsella" To: Subject: GROUPing only those rows that do not contain a NULL field? Date: Fri, 11 Feb 2005 20:44:01 -0000 Organization: Bluefire Systems Ltd MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit X-Mailer: Microsoft Office Outlook, Build 11.0.5510 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180 Thread-Index: AcUQemSGzfFqZBYFTmim4goThJ7+6g== Message-Id: <20050211204404.21ECE8BA15C@svr1.postgresql.org> X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=1.704 tagged_above=0 required=5 tests=MSGID_FROM_MTA_ID X-Spam-Level: * X-Archive-Number: 200502/173 X-Sequence-Number: 20284 Hi I wonder if anyone can help me with a SELECT / GROUP BY problem I'm having. I'm trying to refine a query so that my GROUP BY clause only aggregates rows that have a non-NULL value in one of the fields, leaving other rows 'ungrouped'. An example table, resulting from a LEFT JOIN and subselect on three tables, might be (before grouping) : SELECT user_group_id, user_id, topic_id FROM user_groups NATURAL JOIN users LEFT JOIN (SELECT user_id, topic_id FROM topic_participants WHERE topic_id = 567) AS a USING (user_id) user_group_id | user_id | topic_id ----------------------------------------- 1 101 NULL 1 102 567 1 103 567 2 101 NULL 2 106 567 3 101 NULL 3 104 567 3 102 567 4 103 567 4 104 567 5 105 NULL 6 103 567 6 104 567 (topic id is either a single value, or NULL if the user is not part of the topic) For UI reasons I would like this result collapsed thus: user_group_id | user_id | topic_id ----------------------------------------- 1 101 NULL 1 102 567 1 103 567 2 101 NULL 2 106 567 3 101 NULL 3 104 567 5 105 NULL Note that for all rows where topic_id IS NOT NULL, only one row per user_id is returned (user_group_id is not relevant for these rows). Can this aggregation be achieved with a DISTINCT ON / GROUP BY clause? (Or anything else). I haven't managed to find anything that leaves the NULL-field rows unscathed so far. Thanks in advance for any help! Simon K