【问题标题】:ERROR: division by zero + PostgreSQL + Rails错误:除以零 + PostgreSQL + Rails
【发布时间】:2020-01-17 04:57:46
【问题描述】:

当我在 psql 中运行此数据库视图时出现以下错误(错误:除以零)。即使我无法在 Rails 控制台中访问我的表格如果有人对此错误有任何解决方案,请对此发表评论,这将非常有帮助,提前谢谢。

select 
      (exam_id || '00' || quarter)::bigint as id,
      account_id,
      exam_id,
      quarter,
      quarter_label,
      count(id) as assessments,
      max(banding_percentage) as top_assessment_percentage,
      min(banding_percentage) as bottom_assessment_percentage,
      round(avg(banding_percentage),2) as avg_assessment_percentage
    from report_assessments
    group by account_id, exam_id, quarter, quarter_label;

【问题讨论】:

  • @JimJones 实际上我没有把那个条件设为 NULLIF 我做了我的价值的解决方案,它永远不会变成 0。
  • 如果你完全控制了这个变量,那就没什么好担心的了。但是,如果在除法中得到零的可能性很小,那么 nullif 的使用势在必行。
  • @JimJones 是的,谢谢。

标签: sql ruby-on-rails postgresql view


【解决方案1】:

为避免遇到division by zero 异常,您应该使用nullif,以便您可以捕获此0 并将其替换为null,例如

WITH j (v1,v2) AS (
  VALUES (1.0,0.0),(10.0,3.0)
) 
SELECT v1/nullif(v2,0) AS div FROM j;

        div         
--------------------

 3.3333333333333333
(2 Zeilen)

【讨论】:

  • @ShubhamSingh 。 . .这是规范的解决方案,应该接受答案。
【解决方案2】:

你需要做这样的事情。 它适用于我的情况:

Negotiation.find(
  :all, 
  conditions: conditions_hash('negotiation'),
  select: 
    'CASE 
      sum(banding_percentage) 
      WHEN 
        0 
      THEN 
        NULL 
      ELSE 
        sum(total_percentage) / sum(banding_percentage) 
      END as error_check'
).first

【讨论】:

  • 你能检查我刚刚上传的屏幕截图无法从 Rails 控制台访问我的表格
猜你喜欢
  • 1970-01-01
  • 2014-04-08
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
相关资源
最近更新 更多