Search Postgresql Archives

Re: getting around---division by zero on numeric

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Tim Nelson <timnelson@xxxxxxxxxxxx> writes:
> I am getting division by zero on a calculated field ( sum(sales) is 0 ) 
> and I can't find a way around this.  I figured out you can't use an 
> aggregate in a where, and using having the parser must (obviously) 
> evaluate the select fields before considering teh having clause.

Nothing "obvious" about that, in fact the spec says the opposite.

> select
> 	type,
> 	sum(sales),
> 	sum(cost),
> 	(sum(sales) * sum(cost) / sum(sales)) * 100
> from test
> group by 1
> having sum(sales) != 0

This should indeed work.  If it doesn't, it means you are using an old
version of Postgres.  It was fixed in 7.4.4:

2004-07-10 14:39  tgl

	* src/backend/executor/: nodeAgg.c (REL7_4_STABLE), nodeAgg.c: Test
	HAVING condition before computing targetlist of an Aggregate node. 
	This is required by SQL spec to avoid failures in cases like  
	SELECT sum(win)/sum(lose) FROM ... GROUP BY ... HAVING sum(lose) >
	0; AFAICT we have gotten this wrong since day one.  Kudos to Holger
	Jakobs for being the first to notice.

As other respondents noted, you can work around the problem in various
ways ... but you shouldn't have to.

			regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 3: Have you checked our extensive FAQ?

               http://www.postgresql.org/docs/faq

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux