PostgreSQL 视图错误处理

PostgreSQL View Error Handling

下面给出的代码是我创建的视图的一部分。但有时它可能会抛出一个错误:

division by zero

这个错误的原因是 sum(bills.past_arrear) 部分可能在某些月份为 0。

SELECT (SELECT revenue_driver.driver_id 
        FROM ccdb.revenue_driver 
        WHERE revenue_driver.driver_desc::text = 'Arrear Collection Efficiency'::text) AS driver_id
       ,bills.org_unit_id::integer AS section_id
       ,date_part('Month'::text, bills.due_date) AS mnth
       ,date_part('Year'::text, bills.due_date) AS yr
       ,ROUND(SUM(COALESCE(bills.arrear_collected,0::numeric))/sum(bills.past_arrear)*100::numeric, 2) AS per_efficiency
       ,now() AS creation_dt
FROM ccdb.bills
WHERE bills.due_date::date >= date_trunc('Month'::text,'now'::text::date::timestamp with time zone)::date
AND bills.due_date::date <= 'now'::text::date
AND (bills.bill_type_group_code::text = ANY (ARRAY['EB'::character varying::text, 'Energy'::character varying::text]))
GROUP BY bills.org_unit_id, date_part('Year'::text, bills.due_date), date_part('Month'::text, bills.due_date);

我想要的是 if ROUND(SUM(COALESCE(bills.arrear_collected,0::numeric))/sum(bills.past_arrear)*100::numeric, 2) 抛出 除以零 错误我想用 0 替换该值。

我不知道如何处理这个错误。请有人帮助我。

您需要在 select 语句中使用 CASE WHEN,如下所示:-

CASE 
    WHEN sum(bills.past_arrear) = 0
    THEN 0
    ELSE ROUND(SUM(COALESCE(bills.arrear_collected, 0::NUMERIC)) / sum(bills.past_arrear) * 10 ‌​0::NUMERIC, 2)
END AS per_efficiency