PostgreSQL:在使用case语句时如何避免被零除

时间:2016-07-06 00:33:37

标签: sql postgresql

我试图划分两个案例陈述。如何避免偶尔除零?我似乎无法弄清楚NULLIF方法。

 SELECT
           ROUND(100 * SUM(CASE WHEN be.event IN ('a') THEN 1 ELSE 0 END) / SUM(CASE WHEN be.event IN ('b', 'a') THEN 1 ELSE 0 END), 2)  AS "% Instant Book Today"
    FROM booking_events be
    WHERE
          be.created_at >= current_date AND
          be.created_at < current_date + interval '1 day';

解决此问题的最有效方法是什么?

1 个答案:

答案 0 :(得分:4)

您可以将NULLIF()用作:

SELECT ROUND(100 * SUM(CASE WHEN be.event IN ('a') THEN 1 ELSE 0 END) / 
                   NULLIF(SUM(CASE WHEN be.event IN ('b', 'a') THEN 1 ELSE 0 END), 0), 2
            ) AS "% Instant Book Today"

或者,分母总是非负数,只需删除ELSE 0

SELECT ROUND(100 * SUM(CASE WHEN be.event IN ('a') THEN 1 ELSE 0 END) / 
                   SUM(CASE WHEN be.event IN ('b', 'a') THEN 1 END), 2
            ) AS "% Instant Book Today"

或者,将查询写为:

SELECT ROUND(AVG(CASE WHEN be.event IN ('a') THEN 100.0 ELSE 0 END),
             2) as "% Instant Book Today"
FROM booking_events be
WHERE be.created_at >= current_date AND
      be.created_at < current_date + interval '1 day' AND
      be.event IN ('a', 'b');