[英]PostgreSQL: How to avoid division by zero when using case statements
I am trying to divide two case statements. 我试图将两个案例陈述分开。 How do I avoid the occasional division by zero?
如何避免偶数除以零? I couldn't seem to figure out the
NULLIF
method. 我似乎无法弄清楚
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';
What is the most efficient way of solving this problem? 解决此问题的最有效方法是什么?
You can use NULLIF()
as: 您可以将
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"
Or, alternatively, the denominator is always non-negative, just remove the ELSE 0
: 或者,分母始终为非负数,只需删除
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"
Or, write the query as: 或者,将查询编写为:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.