X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 3A67BD1B215 for ; Sun, 13 Jun 2004 10:46:17 -0300 (ADT) 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 00718-05 for ; Sun, 13 Jun 2004 13:46:15 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id CFDA5D1B269 for ; Sun, 13 Jun 2004 10:46:09 -0300 (ADT) Received: (qmail 3708 invoked by uid 500); 13 Jun 2004 13:52:12 -0000 Date: Sun, 13 Jun 2004 08:52:12 -0500 From: Bruno Wolff III To: Vitaly Belman Cc: pgsql-performance@postgresql.org Subject: Re: Additional select fields in a GROUP BY Message-ID: <20040613135212.GA3260@wolff.to> Mail-Followup-To: Vitaly Belman , pgsql-performance@postgresql.org References: <2393942843.20040613062117@012.net.il> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <2393942843.20040613062117@012.net.il> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200406/143 X-Sequence-Number: 7201 On Sun, Jun 13, 2004 at 06:21:17 +0300, Vitaly Belman wrote: > > Consider the following query: > > select t1field1, avg(t2fieild2) > from t1, t2 > where t1.field1 = t2.field2 > group by t1field1 > > That works fine. But I'd really like to see more fields of t1 in this > query, however I can't add them into the select because they're not > part of the GROUP BY, thus I have to add them to there too: If t1.field1 is a candiate key for t1, then the normal thing to do is to group t2 by t2.field1 (assuming you really meant to join on t2.field1, not t2.field2) and THEN join to t1. That may even be faster than the way you are doing things now. So the query would look like: SELECT t1.field1, t1.field2, t1.field3, a.t2avg FROM t1, (SELECT field1, avg(field2) as t2avg FROM t2 GROUP BY field1) as a WHERE t1.field1 = a.field1