gpt4 book ai didi

ruby-on-rails - rails : prevent division by zero with postgres

转载 作者:行者123 更新时间:2023-11-29 12:29:04 25 4
gpt4 key购买 nike

我有一个带有 postgre 数据库的 Rails 应用程序,我正在尝试使用以下语句获取一些指标

Negotiation.find(:all, :conditions => conditions_hash('negotiation'), :select => 'sum(payment_term * amount_after_annualised_base) / sum(amount_after_annualised_base) as pt').first

我如何确保 sum(amount_after_annualised_base) 不为 0(因此不会引发“被零除”错误)?

我找到了这个,但不确定它是否正确/最好/最有效的方法。

Negotiation.find(:all, :conditions => conditions_hash('negotiation'), :select => 'sum(payment_term * amount_after_annualised_base) / (CASE sum(amount_after_annualised_base) WHEN 0 THEN NULL ELSE sum(amount_after_annualised_base) END) as pt').first

谢谢!皮埃尔

最佳答案

使用nullif :

Negotiation.find(:all, :conditions => conditions_hash('negotiation'), :select => 'sum(payment_term * amount_after_annualised_base) / nullif(sum(amount_after_annualised_base),0) as pt').first

这只是您解决方案的简写形式:

Negotiation.find(:all, :conditions => conditions_hash('negotiation'), :select => 'sum(payment_term * amount_after_annualised_base) / (CASE sum(amount_after_annualised_base) WHEN 0 THEN NULL ELSE sum(amount_after_annualised_base) END) as pt').first

关于ruby-on-rails - rails : prevent division by zero with postgres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5154397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com