Received: from echna.ne.jp (echna.ne.jp [210.175.52.4]) by postgresql.org (8.11.3/8.11.4) with ESMTP id fBCG1dm61346 for ; Wed, 12 Dec 2001 11:01:39 -0500 (EST) (envelope-from rk73@echna.ne.jp) Received: from VIP333 [210.175.55.222] by echna.ne.jp with ESMTP (SMTPD32-6.06) id AF94EFAF024E; Thu, 13 Dec 2001 01:02:28 +0900 Date: Thu, 13 Dec 2001 01:02:25 +0900 From: Masaru Sugawara To: Mr OCP Subject: Re: Please help me write this query or function Cc: pgsql-admin@postgresql.org In-Reply-To: <20011211125445.96186.qmail@web20609.mail.yahoo.com> References: <20011211125445.96186.qmail@web20609.mail.yahoo.com> Errors-To: Message-Id: <20011213003129.4D56.RK73@echna.ne.jp> MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Mailer: Becky! ver. 2.00.06 X-Archive-Number: 200112/89 X-Sequence-Number: 2812 On Tue, 11 Dec 2001 23:54:45 +1100 (EST) Mr OCP wrote: > Hi > > We have a table like follows: > > id, account_name, amount, action_type > > The amount field has both debit and credit entires and > action_type defines the type of transaction ( debit or > credit), debit entries have negative '-' symbol before > the amount. > > where there are multipble transaction for the same id, > I need to write a query as under: > > select id, amount(credit), amount(debit), amount > credit - amount debit from table where id is the same; > > Its making it difficult for me because the amount > field has both debit and credit entries, your ideas, > codes or sql will be much appreciated. > Would you care to use a UNION clause in a sub-select to divide the amount column (with both debit and credit entries) into the different fields ? And if you have a large number of rows in the table, you might create an index on the action_type and id columns. A query example is: drop table account; drop index idx_account_id; create table account (id int4 not null, account_name text default null, amount int4 not null, action_type varchar(10) not null, check(action_type in ('credit','debit')) ); create index idx_account_id_action on account (id, action_type); insert into account values(1, '', 100, 'credit'); insert into account values(2, '', 200, 'credit'); insert into account values(2, '', 100, 'debit'); insert into account values(2, '', 200, 'debit'); insert into account values(3, '', 100, 'debit'); select t.id, sum(t.c) as credit, -sum(t.d) as debit, sum(t.c) - sum(t.d) as total from (select id, amount as c, 0 as d from account where action_type = 'credit' union all select id, 0, amount from account where action_type = 'debit' ) as t group by t.id Regards, Masaru Sugawara