查询在PostgreSQL中给出除零错误

时间:2014-03-05 19:40:20

标签: sql postgresql percentage postgresql-9.2

我正在尝试运行以下查询,这导致我postgres error: division by zero

select 
    request_count,
    response_count, 
    (response_count*100) / (request_count+response_count) AS proportion 
from total_dummy_table; 

如何避免和解决division by zero错误?

尝试使用以下查询修复,但获得与上面相同的结果

SELECT 
    request_count,
    response_count,
    (response_count*100) / (request_count) AS proportion 
FROM 
    total_dummy_table
ORDER BY 
    (response_count*100) /(CASE request_count WHEN 0 Then NULL ELSE request_count END) DESC NULLS FIRST

请告诉我我在哪里做错了,或者我该如何解决这个问题。 谢谢!

结果期望:

查询应该返回如下内容:

Request_count | Response_count | Proportion

1603423       |  585706        | 36.52

快速注释:表total_dummy_table没有列名proportion,它是结果的加法,其中包含计算比例。

2 个答案:

答案 0 :(得分:21)

使用NULLIF

something/NULLIF(column_name,0)

NULLIF(col,val)

的简写
CASE WHEN col=val THEN NULL ELSE col

答案 1 :(得分:7)

select request_count,response_count, 
case 
    when 
    request_count+response_count = 0 then 0 
    else
(response_count*100) / (request_count+response_count) 
end AS proportion 
from total_dummy_table;