2016-01-13 26 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