2011-03-01 81 views
1

我有我的軌道與postgre數據庫應用程序,我試圖得到一些指標,用下面的語句Rails的:防止被零除在Postgres

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

我怎麼能確保總和(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 

謝謝! 皮埃爾

回答

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 

這僅僅是你的解決方案consise速記:

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 
+0

這是行不通的?因爲你仍然試圖在所有情況下進行分工。 – nathanvda 2011-03-01 14:12:36

+0

它實際上工作。爲了簡明起見,我拿這個 – Pierre 2011-03-01 18:52:36

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爲零。

+0

不錯,使用最大(1,sum_amount)是最酷的方式。謝謝。 – Fred 2013-04-09 15:58:36

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,否則請求的divis離子。