pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: rodgerd@diaspora.gen.nz
Cc: pgsql-sql@postgresql.org
Subject: Re: Applying SUM twice in the same query.
Date: Sat, 15 Jul 2000 11:59:42 -0400
Message-ID: <2036.963676782@sss.pgh.pa.us> (raw)
In-Reply-To: <20000715173124.A5793@diaspora.gen.nz>
References: <20000715173124.A5793@diaspora.gen.nz>

Rodger Donaldson <rodgerd@diaspora.gen.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



view thread (2+ messages)

Message-ID: <2036.963676782@sss.pgh.pa.us>
Permalink:  ../2036.963676782@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/2036.963676782@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, rodgerd@diaspora.gen.nz
  Subject: Re: Applying SUM twice in the same query.
  In-Reply-To: <2036.963676782@sss.pgh.pa.us>
  References: <20000715173124.A5793@diaspora.gen.nz> <2036.963676782@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox