【问题标题】:How do I find the percentage between two columns in postgresql?如何在 postgresql 中找到两列之间的百分比?
【发布时间】:2016-04-17 20:49:13
【问题描述】:

我的 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 以获得已声明代码的百分比。

我尝试了很多东西,但总是得到错误:

错误:除以零

查询失败。

我最近的尝试使用了以下内容:

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

非常感谢任何帮助和指导!

【问题讨论】:

  • 在什么情况下codes_allocated可以为0?也许您应该过滤掉codes_allocated 为0 的行。
  • 添加新产品或将代码传输到另一个系统时,计数可能会降至零。一个好主意,但我还不确定如何解决。会做一些挖掘。

标签: sql database postgresql percentage


【解决方案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,则将保留代码计数除以总代码计数。否则,值为空(不会除数?
  • @Jacktheyeti 正确,为了清楚起见,我包含了 ELSE 部分,但这是您可以删除它的默认返回值,并且完全相同
【解决方案2】:

我认为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)

【讨论】:

  • 使用 avg() 函数成功。但是,它增加了一些时间来完成查询。
  • @Jacktheyeti 。 . .这是令人惊讶的。还有多少时间?
  • ~2.这可能是我完整查询的性质。我有一个相当大的查询,这里没有显示多个连接和计算
  • @Jacktheyeti 。 . .我希望执行时间与进行显式除法无法区分。可能会有一些有益的计算机指令,一种或另一种方式,但很难说哪个更快或更慢可以忽略不计。
  • 我可能不正确地说它增加了查询时间。我道歉。我只是根据我的 sql 客户端中记录的时间记录了完成查询所需的时间。
猜你喜欢
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2023-01-08
  • 2017-05-17
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
  • 2013-05-07
相关资源
最近更新 更多