按价格排序时,SQL除以零

时间:2018-03-22 19:28:57

标签: sql postgresql

为什么我在这个SQL中得到除零?

我尝试了很多,比如演员,NULLIF以及那些东西,但没有任何作用。

$sql = "SELECT *, (cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount FROM products ORDER BY CAST(price AS Float) asc LIMIT $no_of_records_per_page OFFSET $offset";

如果我踢了

(cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount

比它的工作。

但是如果我踢出来它也会起作用

ORDER BY CAST(price AS Float) asc

但我需要他们两个......我尝试了很多,但无法解决它......

2 个答案:

答案 0 :(得分:0)

我不确定这是否是最优雅的解决方案,但在开始时检查pricebefore = 0应该解决它...

SELECT *, case when pricebefore = 0 
    then 0 --or you might want 1 or 100 here?
    else (cast(price as numeric(20, 4))*100)
 /cast(pricebefore as numeric(20, 4)) - 100 end AS discount 
FROM products ORDER BY CAST(price AS Float) asc

答案 1 :(得分:0)

如果pricebefore为零(任何被转换为0,如" 0"或0或NULL或""),你将得到它 - 如果你只是想摆脱崩溃,你可以使用GREATEST函数1,如/GREATEST(cast(pricebefore as numeric(20, 4)),1) - 或者因为4个可能的小数,你也可以使用,0.0001,我想..但我怀疑你的之后的计算将是准确的。