PostgreSQL division by zero when ordering

依然范特西╮ 提交于 2019-12-10 19:20:01

问题


i need to execute this query in postgres but i couldn't get rid of this error

    ERROR: division by zero
SQL state: 22012

here is the query :

select id,rates_sum,rates_count from tbl_node  order by rates_sum/rates_count DESC;

i know i can add a small value to the rates_count but i get inaccurate values .

Is there a way to make the postgres ignore this error ,or using if statement to check zeros and replace them with any number. and again the error in the order by clause.

Thanks


回答1:


Use a CASE statement:

SELECT 
    id,
    rates_sum,
    rates_count 
FROM 
    tbl_node  
ORDER BY 
    rates_sum / (CASE rates_count WHEN 0 THEN NULL ELSE rates_count END) DESC NULLS FIRST;

You could also use NULLS LAST, if you want to.




回答2:


how about a where rates_count != 0?



来源:https://stackoverflow.com/questions/4067742/postgresql-division-by-zero-when-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!