From: | Chester Kustarz <chester(at)arbor(dot)net> |
---|---|
To: | Greg Donald <destiney(at)gmail(dot)com> |
Cc: | pgsql-general <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: division by zero issue |
Date: | 2004-09-15 19:26:30 |
Message-ID: | Pine.BSO.4.44.0409151353010.26903-100000@detroit.arbor.net |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On Wed, 15 Sep 2004, Greg Donald wrote:
> Converting some MySQL code to work with Postgres here.
>
> I have this query:
>
> SELECT
> tasks.task_id,
> (tasks.task_duration * tasks.task_duration_type /
> count(user_tasks.task_id)) as hours_allocated
> FROM tasks
> LEFT JOIN user_tasks
> ON tasks.task_id = user_tasks.task_id
> WHERE tasks.task_milestone = '0'
> GROUP BY
> tasks.task_id,
> task_duration,
> task_duration_type
> ;
>
> The problem is that sometimes count(user_tasks.task_id) equals zero,
> so I get the division by zero error. Is there a simple way to make
> that part of the query fail silently and just equal zero instead of
> dividing and producing the error?
you can avoid it by using the CASE statement:
SELECT
tasks.task_id,
case when count(user_tasks.task_id) > 0 then
(tasks.task_duration * tasks.task_duration_type /
count(user_tasks.task_id)) else 0.0 end as hours_allocated
FROM tasks
LEFT JOIN user_tasks
ON tasks.task_id = user_tasks.task_id
WHERE tasks.task_milestone = '0'
GROUP BY
tasks.task_id,
task_duration,
task_duration_type
;
alternatively you might use HAVING:
SELECT task_id, task_duration * task_duration_type / num_tasks as
hours_allocated
FROM (
SELECT
tasks.task_id,
tasks.task_duration, tasks.task_duration_type,
count(user_tasks.task_id) as num_tasks
FROM tasks
LEFT JOIN user_tasks
ON tasks.task_id = user_tasks.task_id
WHERE tasks.task_milestone = '0'
GROUP BY
tasks.task_id,
task_duration,
task_duration_type
HAVING count(user_tasks.task_id) > 0
) t
;
From | Date | Subject | |
---|---|---|---|
Next Message | Chester Kustarz | 2004-09-15 19:34:31 | Re: division by zero issue |
Previous Message | Marc Slemko | 2004-09-15 19:13:54 | Re: disk performance benchmarks |