Rails: prevent division by zero with postgres

筅森魡賤 提交于 2021-01-28 12:57:37

问题


I have my rails app with a postgre database and I'm trying to get some indicators, with the following statement

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

how can I make sure that sum(amount_after_annualised_base) is not 0 (thus doesn't throw a "division by zero" error)?

I've found this, but not sure it is correct / the best / most efficient way.

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

thanks! Pierre


回答1:


use 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

which is just a consise shorthand for your solution:

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



回答2:


How about:

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

and check in your code if sum_amount is zero.




回答3:


I think you would need to write something like

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

which would return NULL if sum(amount_after_annualised_base) is zero, and else does the requested division.



来源:https://stackoverflow.com/questions/5154397/rails-prevent-division-by-zero-with-postgres

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