X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id 383FAD1B53E for ; Wed, 15 Oct 2003 20:31:58 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 23399-08 for ; Wed, 15 Oct 2003 17:31:29 -0300 (ADT) Received: from polaris.pinpointresearch.com (66-7-238-130.cust.telepacific.net [66.7.238.130]) by svr1.postgresql.org (Postfix) with ESMTP id 10686D1B4F2 for ; Wed, 15 Oct 2003 17:31:26 -0300 (ADT) Received: from betelgeuse.pinpointresearch.com (betelgeuse.pinpointresearch.com [192.168.1.179]) by polaris.pinpointresearch.com (Postfix) with ESMTP id 83AFA103C7; Wed, 15 Oct 2003 13:31:22 -0700 (PDT) From: Steve Crawford Organization: Pinpoint Research To: "Muhyiddin A.M Hayat" , Subject: Re: Calc Date: Wed, 15 Oct 2003 13:31:22 -0700 User-Agent: KMail/1.5.1 References: <002e01c39356$d5885ca0$1f00a8c0@middinkcomp> In-Reply-To: <002e01c39356$d5885ca0$1f00a8c0@middinkcomp> MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200310151331.22516.scrawford@pinpointresearch.com> X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200310/180 X-Sequence-Number: 15580 On Wednesday 15 October 2003 12:59 pm, Muhyiddin A.M Hayat wrote: > Dear all, > > I have below table > > +-----+--------------------+---------------------+ > > | id | db |cr | > > +-----+--------------------+---------------------+ > > |1 | | 200 | > |2 | 100 | | > |3 | 100 | | > |4 | 150 | | > |5 | | 200 | > > I Would like to calc that balance, and look like > > +-----+--------------------+---------------------+-----------+ > > | id | db |cr | > | bal | > > +-----+--------------------+---------------------+-----------+ > > |1 | | 200 > | |200 | 2 | 100 | > | |100 | 3 | 100 | > | |0 | 4 | 150 > | | |-150 | 5 | > | | 200 |50 | > > What can I do to get result like that Something like this: select id,db,cr,(select sum(cr-db) from calc sub where sub.id <= calc.id) from calc; This of course assumes that ID indicates the correct order of the entries and it will blow up if you allow nulls for cr or db (which you shouldn't since that would literally be interpreted as "they withdrew 10 and deposited an unknown amount"). If you have null values already and they should be interpreted as 0 just do this: select id, db, cr, (select sum(coalesce(cr,0)-coalesce(db,0)) from calc sub where sub.id <= calc.id) from calc; I assume no responsibility for potential lack of scalability of this query. :) It's quite possible a faster solution exists - we'll see what comes up on the list. Cheers, Steve