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 3DD8752A79 for ; Fri, 8 Jul 2005 11:07:10 -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 31283-07 for ; Fri, 8 Jul 2005 14:07:08 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.197.194]) by svr1.postgresql.org (Postfix) with SMTP id 6196052A06 for ; Fri, 8 Jul 2005 11:07:00 -0300 (ADT) Received: (qmail 22864 invoked by uid 500); 8 Jul 2005 14:07:25 -0000 Date: Fri, 8 Jul 2005 09:07:25 -0500 From: Bruno Wolff III To: PFC Cc: Kenneth Gonsalves , Ramakrishnan Muralidharan , pgsql-sql@postgresql.org Subject: Re: two sums in one query Message-ID: <20050708140725.GA22725@wolff.to> Mail-Followup-To: Bruno Wolff III , PFC , Kenneth Gonsalves , Ramakrishnan Muralidharan , pgsql-sql@postgresql.org References: <02767D4600E59A4487233B23AEF5C5992A4093@blrmail1.aus.pervasive.com> <200507081306.08597.lawgon@thenilgiris.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.11 tagged_above=0 required=5 tests=AWL, UPPERCASE_25_50 X-Spam-Level: X-Archive-Number: 200507/68 X-Sequence-Number: 22046 On Fri, Jul 08, 2005 at 15:49:20 +0200, PFC wrote: > > > >> SELECT SUM( CASE WHEN COALESCE( DEBIT , 0 ) <> 0 THEN > >>COALESCE( AMOUNT , 0 ) ELSE 0 END ) AS DEBIT_AMT , SUM( CASE WHEN > >>COALESCE( CREDIT , 0 ) <> 0 THEN COALESCE( AMOUNT , 0 ) ELSE 0 > >>END ) AS CREDIT_AMT FROM > > I don't know if it will use indexes (bitmapped OR indexes in 8.1 > ?)... if you have indexes on debit and on credit, you could do > > SELECT (SELECT sum(amount) FROM table WHERE debit=X) AS debit, (SELECT > sum(amount) FROM table WHERE credit=x) AS credit; If most of the records are credits or debits you don't want to do this. A single sequential scan through the table will be the best plan.