Re: Applying SUM twice in the same query.

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: rodgerd(at)diaspora(dot)gen(dot)nz
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Applying SUM twice in the same query.
Date: 2000-07-15 15:59:42
Message-ID: 2036.963676782@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Rodger Donaldson <rodgerd(at)diaspora(dot)gen(dot)nz> writes:
> What I really want to do with total is to derive a
> proportion of number of server:number of servers, something like:

Only way to do that is with a sub-select, because all the aggregates
appearing in a single query are going to be computed over the same
input set(s). Try

select
server_name,
sum(number) AS number,
(select sum(number) from web_servers) AS total
from web_servers
group by server_name;

While this looks like it might be inefficient, it's really not because
Postgres recognizes that the inner select is independent of the outer
and only evaluates it once.

Note you need PG 7.0 or later to do this.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Prasanth A. Kumar 2000-07-15 17:11:43 Select by priority
Previous Message Rodger Donaldson 2000-07-15 05:31:25 Applying SUM twice in the same query.