X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (mx2.hub.org [200.46.204.254]) by postgresql.org (Postfix) with ESMTP id E073E11F8B99 for ; Fri, 21 Apr 2006 05:54:38 -0300 (ADT) X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Score: -2.599 X-Spam-Level: X-Spam-Status: No, score=-2.599 required=5 tests=[BAYES_00=-2.599] Received: from postgresql.org ([200.46.204.71]) by localhost (mx2.hub.org [200.46.204.254]) (amavisd-new, port 10024) with ESMTP id uSnoh3kWcXyB for ; Fri, 21 Apr 2006 05:54:31 -0300 (ADT) X-Greylist: delayed 00:17:32.05536 by SQLgrey- Received: from svr4.postgresql.org (svr4.postgresql.org [66.98.251.159]) by postgresql.org (Postfix) with ESMTP id 2357B11F872A for ; Fri, 21 Apr 2006 05:54:28 -0300 (ADT) Received: from rzcomm22.rz.tu-bs.de (rzcomm22.rz.tu-bs.de [134.169.9.68]) by svr4.postgresql.org (Postfix) with ESMTP id 151C65AF9E3 for ; Fri, 21 Apr 2006 08:36:56 +0000 (GMT) Received: from [134.169.64.209] (imt81.imt.ing.tu-bs.de [134.169.64.209]) by rzcomm22.rz.tu-bs.de (8.13.4/8.13.4) with ESMTP id k3L8ap0W012001 for ; Fri, 21 Apr 2006 10:36:52 +0200 (envelope-from jdi@l4x.org) Message-ID: <444899B6.6090001@l4x.org> Date: Fri, 21 Apr 2006 10:37:10 +0200 From: Jan Dittmer User-Agent: Debian Thunderbird 1.0.7 (X11/20051017) X-Accept-Language: en-us, en MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: Better way to write aggregates? Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Archive-Number: 200604/494 X-Sequence-Number: 18578 Hi, I more or less often come about the problem of aggregating a child table counting it's different states. The cleanest solution I've come up with so far is: BEGIN; CREATE TABLE parent ( id int not null, name text not null, UNIQUE(id) ); CREATE TABLE child ( name text not null, state int not null, parent int not null references parent(id) ); CREATE VIEW parent_childs AS SELECT c.parent, count(c.state) as childtotal, count(c.state) - count(nullif(c.state,1)) as childstate1, count(c.state) - count(nullif(c.state,2)) as childstate2, count(c.state) - count(nullif(c.state,3)) as childstate3 FROM child c GROUP BY parent; CREATE VIEW parent_view AS SELECT p.*, pc.* FROM parent p LEFT JOIN parent_childs pc ON (p.id = pc.parent); COMMIT; Is this the fastest way to build these aggregates (not considering tricks with triggers, etc)? The count(state) - count(nullif(...)) looks a bit clumsy. I also experimented with a pgsql function to sum these up, but considered it as not-so-nice and it also always forces a sequential scan on the data. Thanks for any advice, Jan