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 869C65E46E7 for ; Fri, 27 Aug 2004 12:44:01 -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 54075-02 for ; Fri, 27 Aug 2004 15:44:03 +0000 (GMT) Received: from davinci.ethosmedia.com (server226.ethosmedia.com [209.128.84.226]) by svr1.postgresql.org (Postfix) with ESMTP id 0AB2C5E46D2 for ; Fri, 27 Aug 2004 12:43:55 -0300 (ADT) Received: from [63.195.55.98] (HELO spooky) by davinci.ethosmedia.com (CommuniGate Pro SMTP 4.1.8) with ESMTP id 6191192; Fri, 27 Aug 2004 08:45:19 -0700 Content-Type: text/plain; charset="iso-8859-1" From: Josh Berkus Organization: Aglio Database Solutions To: Scott Gerhardt Subject: Re: Aggregate query for multiple records Date: Fri, 27 Aug 2004 08:43:32 -0700 User-Agent: KMail/1.4.3 References: <641FEEDD-F728-11D8-A763-000393801C60@g-it.ca> <200408262155.42636.josh@agliodbs.com> <187ADA81-F7F3-11D8-A763-000393801C60@g-it.ca> In-Reply-To: <187ADA81-F7F3-11D8-A763-000393801C60@g-it.ca> Cc: pgsql-sql@postgresql.org MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <200408270843.32059.josh@agliodbs.com> X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.3 tagged_above=0.0 required=5.0 tests=UPPERCASE_25_50 X-Spam-Level: X-Archive-Number: 200408/303 X-Sequence-Number: 18800 Scott, > > SELECT wid, > > (SELECT SUM(oil) FROM prd_data pd2 > > WHERE pd2.wid = prd_data.wid ORDER BY "date" LIMIT 6) as tot_oil, > > (SELECT SUM(hours) FROM prd_data pd2 > > WHERE pd2.wid = prd_data.wid ORDER BY "date" LIMIT 6) as tot_hours > > FROM prd_data > > ORDER BY wid; > > There is only one table being queried (prd_data). What is the purpose > of "pd2"? It's a table alias. There may be only one table, but to do this in a single query you need to reference 3 "instances" of that same table. Hmmm ... let me make the distinction more clear: SELECT wid, (SELECT SUM(oil) FROM prd_data prd2 WHERE prd2.wid = prd1.wid ORDER BY "date" LIMIT 6) as tot_oil, (SELECT SUM(hours) FROM prd3 WHERE prd3.wid = prd1.wid ORDER BY "date" LIMIT 6) as tot_hours FROM prd_data prd1 ORDER BY wid; -- Josh Berkus Aglio Database Solutions San Francisco