PostgreSQL – 使用SUM意外除零

前端之家收集整理的这篇文章主要介绍了PostgreSQL – 使用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就可以了.

这怎么可能?

我喜欢这个问题,我求助于这些 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

原文链接:https://www.f2er.com/postgresql/191908.html

猜你在找的Postgre SQL相关文章