订购时 PostgreSQL 除以零 [英] PostgreSQL division by zero when ordering

查看:75
本文介绍了订购时 PostgreSQL 除以零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 postgres 中执行这个查询,但我无法摆脱这个错误

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

    ERROR: division by zero
SQL state: 22012

这里是查询:

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

我知道我可以为 rates_count 添加一个小值,但我得到的值不准确.

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

有没有办法让 postgres 忽略这个错误,或者使用 if 语句来检查零并将它们替换为任何数字.和 order by 子句中的错误.

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.

谢谢

推荐答案

使用 CASE 语句:

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;

如果你愿意,你也可以使用 NULLS LAST.

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

这篇关于订购时 PostgreSQL 除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆