Re: Aggregate functions not allowed in WHERE clause

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: pradeep singh <lets_begin_with_me(at)yahoo(dot)com>
Cc: Ricardo Naranjo Faccini <gramo(dot)gnu(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Aggregate functions not allowed in WHERE clause
Date: 2006-06-13 13:52:46
Message-ID: 20060613135246.GA23213@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Jun 12, 2006 at 08:40:29PM -0700, pradeep singh wrote:
> i think this query can be rewritten as
>
> SELECT claim_id,sum(invoices),sum(payments)
> FROM logs
> GROUP BY claim_id
> HAVING sum(invoices) > 0 OR sum(payments) > 0;
>
> having clause can be used with aggregate functions but
> those functions should be the part of column
> list/expression list in the SELECT statement.

PostgreSQL has no such requirement; see "The GROUP BY and HAVING
Clauses" in the documentation:

http://www.postgresql.org/docs/8.1/interactive/queries-table-expressions.html#QUERIES-GROUP

"Tip: Grouping without aggregate expressions effectively calculates
the set of distinct values in a column."

"Note that the aggregate expressions do not necessarily need to be
the same in all parts of the query."

Offhand I don't know if the SQL standard requires expressions in
the HAVING clause to be present in the select list -- can you cite
reference from the standard that supports the assertion that they
should be?

--
Michael Fuhr

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Leif B. Kristensen 2006-06-13 13:55:01 Re: PostgreSQL and Apache
Previous Message jqpx37 2006-06-13 13:36:43 Re: Password for postgresql superuser?