如何找到 postgresql 中两列之间的百分比?
How do I find the percentage between two columns in postgresql?
我的 SELECT 语句中的两个参数是:
count(product_code.code) as codes_allocated
count(case when product_code.taken='TRUE' then product_code.taken end) as codes_claimed
我想在我的 select 语句中再添加一个参数,该语句采用 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`
非常感谢任何帮助和指导!
为什么不包含 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
我认为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)
我的 SELECT 语句中的两个参数是:
count(product_code.code) as codes_allocated
count(case when product_code.taken='TRUE' then product_code.taken end) as codes_claimed
我想在我的 select 语句中再添加一个参数,该语句采用 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`
非常感谢任何帮助和指导!
为什么不包含 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
我认为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)