postgresql除以零错误处理

postgresql division by zero error handling

机油值有时为空。我需要除以零异常和 null 如果运算符仍然给出此错误代码。不确定语法有什么问题。
错误:除以零 SQL 状态:22012

WITH query1 AS (
   SELECT well_id, produced_at, oil,
  (EXTRACT(EPOCH FROM age(produced_at,
                          LAG(produced_at) OVER w))/3600)::int as hourly_rate
                          FROM public.production
WINDOW w AS (PARTITION BY well_id ORDER BY well_id, produced_at 
             ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
     
),
query2 as (
   select Well_id, produced_at, nullif(oil,0), hourly_rate,
   (nullif(oil,0)/hourly_rate*6) as Last_Six_Hours_Of_Production,
   (nullif(oil,0)/hourly_rate*12) as Last_Twelve_Hours_Of_Production
    from query1
)
Select *
from query2; 

我认为您也需要为分母添加一些 NULLIF 验证并添加一个 COALESCE 子句。

WITH query1 AS (
   SELECT well_id, produced_at, oil,
  (EXTRACT(EPOCH FROM age(produced_at,
                          LAG(produced_at) OVER w))/3600)::int as hourly_rate
                          FROM public.production
WINDOW w AS (PARTITION BY well_id ORDER BY well_id, produced_at 
             ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
     
),
query2 as (
   select Well_id, produced_at, nullif(oil,0), hourly_rate,
   COALESCE((nullif(oil,0)/nullif(hourly_rate*6,0)),0) as Last_Six_Hours_Of_Production,
   COALESCE((nullif(oil,0)/nullif(hourly_rate*12,0)),0) as Last_Twelve_Hours_Of_Production
    from query1
)
Select *
from query2;