Re: getting around---division by zero on numeric - Mailing list pgsql-general

From Richard Huxton
Subject Re: getting around---division by zero on numeric
Date
Msg-id 435643A3.9030700@archonet.com
Whole thread Raw
In response to getting around---division by zero on numeric  (Tim Nelson <timnelson@phreaker.net>)
Responses Re: getting around---division by zero on numeric  (Berend Tober <btober@seaworthysys.com>)
List pgsql-general
Tim Nelson wrote:
> I am getting division by zero on a calculated field ( sum(sales) is 0 )

It's a two-stage process, so you'll want a sub-query. Something like:

SELECT
   type,
   tot_sales,
   tot_cost
   ((tot_sales * tot_cost / tot_sales) * 100) AS percent
FROM
(
SELECT
   type, sum(sales) AS tot_sales, sum(cost) AS tot_cost
FROM
   test
GROUP BY
   type
HAVING
   sum(sales) <> 0
) AS base
;

--
   Richard Huxton
   Archonet Ltd

pgsql-general by date:

Previous
From: Sean Davis
Date:
Subject: Re: getting around---division by zero on numeric
Next
From: "Jim Buttafuoco"
Date:
Subject: Re: function that resolves IP addresses