Rails:用postgres防止零除零

时间:2011-03-01 12:16:55

标签: ruby-on-rails postgresql

我的带有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

谢谢! 皮尔

3 个答案:

答案 0 :(得分:4)

使用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

答案 1 :(得分:3)

怎么样:

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

如果sum_amount为零,请检查您的代码。

答案 2 :(得分:2)

我认为你需要写一些像

这样的东西
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

如果sum(amount_after_annualised_base)为零,则返回NULL,否则执行请求的除法。