PostgreSQL - 使用 SUM 意外除以零

PostgreSQL - Unexpected division by zero using SUM

此查询(最小可重现示例):

WITH t as (
    SELECT 3 id, 2 price, 0 amount
)
SELECT 
    CASE WHEN amount > 0 THEN
        SUM(price / amount)
    ELSE
        price
    END u_price
FROM t
GROUP BY id, price, amount

在 PostgreSQL 9.4 上抛出

division by zero

没有 SUM 它有效。

这怎么可能?

我无法理解 "why" 部分,但这里有一个解决方法...

 WITH t as (
      SELECT 3 id, 2 price, 0 amount
 )
 SELECT  SUM(price / case when amount = 0 then 1 else amount end) u_cena
 FROM t
 GROUP BY id, price, amount

或者:您可以使用以下内容并避免 "case"

 SELECT  SUM(price / power(amount,sign(amount))) u_cena
 FROM t
 GROUP BY id, price, amount

我喜欢这个问题,所以我求助于这些 tough guys :

策划者有罪:

A CASE cannot prevent evaluation of an aggregate expression contained within it, because aggregate expressions are computed before other expressions in a SELECT list or HAVING clause are considered

更多详情请见 https://www.postgresql.org/docs/10/static/sql-expressions.html#SYNTAX-EXPRESS-EVAL