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 0B3AF5E46CC for ; Fri, 27 Aug 2004 01:56:08 -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 48240-04 for ; Fri, 27 Aug 2004 04:56:10 +0000 (GMT) Received: from davinci.ethosmedia.com (server226.ethosmedia.com [209.128.84.226]) by svr1.postgresql.org (Postfix) with ESMTP id 9F5445E46C2 for ; Fri, 27 Aug 2004 01:56:01 -0300 (ADT) Received: from [63.195.55.98] (HELO spooky) by davinci.ethosmedia.com (CommuniGate Pro SMTP 4.1.8) with ESMTP id 6187794; Thu, 26 Aug 2004 21:57:26 -0700 Content-Type: text/plain; charset="iso-8859-1" From: Josh Berkus Organization: Aglio Database Solutions To: Scott Gerhardt , pgsql-sql@postgresql.org Subject: Re: Aggregate query for multiple records Date: Thu, 26 Aug 2004 21:55:42 -0700 User-Agent: KMail/1.4.3 References: <641FEEDD-F728-11D8-A763-000393801C60@g-it.ca> In-Reply-To: <641FEEDD-F728-11D8-A763-000393801C60@g-it.ca> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <200408262155.42636.josh@agliodbs.com> 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: 200408/295 X-Sequence-Number: 18792 Scott, > Hello, I am new to the list, my apology if this question is beyond the > scope or charter of this list. We have a charter? Why didn't anyone tell me? > My questions is: > What is the best method to perform an aggregate query to calculate > sum() values for each distinct wid as in the example below, but except > for all wid's (not just WHERE wid='01/1-6-1-30w1/0'). > SELECT > SUM(oil) as sumoil, SUM(hours) as sumhours, > FROM > (SELECT oil, hours prd_data WHERE wid='01/1-6-1-30w1/0' > ORDER BY date LIMIT 6) subtable Your problem here is the "limit 6" There isn't any good+fast way to take only 6 of each thing and total them. Also the above query is missing a FROM clause, so I;ve had to guess at your table name below. Oh, and the word "date" is a reserved word, better to quote it. This is valid, but it won't be fast: 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; However, that will be querying the prd_data table about (distinct wid)*2+1 times. Don't hold your breath. > Also, performance wise, would it be better to build a function for this > query. The table has 9 million records and these aggregate queries > take hours. It might. Not for the summaries themselves (which are fastest as aggregates), but to build a table that has only 6 records per WID. -- Josh Berkus Aglio Database Solutions San Francisco