2016-01-13 27 views
1

兩個參數:如何找到postgresql中兩列之間的百分比?在我的SELECT語句

count(product_code.code) as codes_allocated 
count(case when product_code.taken='TRUE' then product_code.taken end) as codes_claimed 

我想多一個參數添加到我的選擇語句,採用codes_claimed並通過codes_allocated除以它獲得的代碼的百分比要求。

我嘗試過很多事情,但總是出現錯誤:

ERROR: division by zero

Query failed.

我最近嘗試使用以下:

(count(case when core_isvcode.reserved='TRUE' then core_isvcode.reserved end)::decimal/count(core_isvcode.code)::decimal)*100 as Percent_redeemed` 

任何幫助和指導,不勝感激!

+0

'code_allocated'在什麼情況下可以爲0?也許你應該過濾掉'codes_allocated'爲0的行。 – absolutelyNoWarranty

+0

當添加新產品時,或者代碼被傳輸到另一個系統時,計數可以降到零。一個好主意,但我不確定如何解決。會做一些挖掘。 – Jacktheyeti

回答

1

爲什麼不包括CASE驗證count(core_isvcode.code) > 0

CASE WHEN count(core_isvcode.code) > 0 THEN 
    (count(case when core_isvcode.reserved='TRUE' then core_isvcode.reserved end)::decimal 
/count(core_isvcode.code)::decimal)*100 
    ELSE NULL 
END as Percent_redeemed 
+0

這也工作,並添加了最少的時間來完成查詢,謝謝大家的幫助。只是爲了確保我明白這是做什麼......它基本上說,如果計數大於0,然後將保留的代碼計數除以總代碼計數。否則,該值爲空(它不會分割數字? – Jacktheyeti

+0

@Jacktheyeti正確,爲了清楚起見,我包含了「ELSE」部分,但這是您可以將其刪除的默認返回值,並且確切相同 –

0

我覺得nullif()往往是最簡單的方法:

(count(case when core_isvcode.reserved='TRUE' then core_isvcode.reserved end)::decimal/nullif(count(core_isvcode.code)::decimal))*100 as Percent_redeemed 

不過,我覺得avg()是這個計算更簡單:

avg(case when core_isvcode.reserved = 'TRUE' then 100.0 
     when core_isvcode.reserved is null then NULL 
     else 0.0 
    end) 
+0

使用avg( )函數工作成功,但它增加了一點點時間來完成查詢 – Jacktheyeti

+0

@Jacktheyeti ......這是令人驚訝的,還有多少時間呢? –

+0

〜2.它可能是我完整查詢的本質。在這裏沒有顯示多個連接和計算的大型查詢 – Jacktheyeti