Re: two sums in one query

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: PFC <lists(at)boutiquenumerique(dot)com>
Cc: Kenneth Gonsalves <lawgon(at)thenilgiris(dot)com>, Ramakrishnan Muralidharan <ramakrishnanm(at)pervasive-postgres(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: two sums in one query
Date: 2005-07-08 14:07:25
Message-ID: 20050708140725.GA22725@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Fri, Jul 08, 2005 at 15:49:20 +0200,
PFC <lists(at)boutiquenumerique(dot)com> 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 <TABLE NAME>
>
> 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.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Steve Wampler 2005-07-08 14:12:26 Re: Make COUNT(*) Faster?
Previous Message PFC 2005-07-08 13:49:20 Re: two sums in one query