Received: from maia.hub.org (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 32FC4632F49 for ; Fri, 9 Apr 2010 04:24:44 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 39098-07 for ; Fri, 9 Apr 2010 07:24:30 +0000 (UTC) X-Greylist: delayed 00:06:39.064042 by SQLgrey-1.7.6 Received: from kracon.net (kracon.net [81.7.185.66]) by mail.postgresql.org (Postfix) with ESMTP id EEEE5632886 for ; Fri, 9 Apr 2010 04:24:32 -0300 (ADT) Received: (qmail 7993 invoked from network); 9 Apr 2010 07:17:50 -0000 Received: from unknown (HELO ?127.0.0.1?) (127.0.0.1) by localhost with SMTP; 9 Apr 2010 07:17:50 -0000 Message-ID: <4BBED49D.7080501@krap.dk> Date: Fri, 09 Apr 2010 09:17:49 +0200 From: Svenne Krap User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.9) Gecko/20100408 Lightning/1.0b2pre Thunderbird/3.0.4 MIME-Version: 1.0 To: sql pgsql Subject: Cascading sum in tree with CTE? Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-0.092 tagged_above=-10 required=5 tests=AWL=-0.092 X-Spam-Level: X-Archive-Number: 201004/34 X-Sequence-Number: 33961 Hi . My problem resembles this: I have the following (simplified) tables 1) create table account ( id serial, name varchar, parent_id int4 references account, primary key (id)) 2) create table transaction (id serial, account_id int4 references account, memo varchar, debet, credit, primary key(id)) So a basic ledger system, with a tree of accounts and transactions on them. Some accounts have transactions others doesn't. I have written a CTE which generates the tree, but I would like to append to each line the sum of all debits and credits of this and all sub accounts. I think it sould be doable, but cannot bend my brain around it and my google-fu has come out short. Say the data was: Account: 1, 'Expenses', null 2, 'IRS', 1 3, '7-Eleven' Transaction: 1, 2, 'Tax Jan 10', null, 100 2, 2, 'Tax Feb 10', null, 120 3, 2, 'Tax Feb 10 correction', 10,null 4, 3, 'Sodas', 10, null 5, 3, 'Beer', 5, null I would expect a tree like: 1, Debt, 25, 220 2, IRS, 10, 220 3, 7-eleven, 15, 0 Is there any way around a writing a stored procedure for that? My current CTE works top down ( top > Expenses > 7-elven) and writes out "paths" to the leaves (ie "Expenses -> 7-Eleven" instead of just 7-Eleven) Svenne