aggregate of an empty result set

后端 未结 4 1666
一向
一向 2021-02-13 19:17

I would like the aggregates of an empty result set to be 0. I have tried the following:

SELECT SUM(COALESCE(capacity, 0))
  FROM objects
 WHERE null IS NOT NULL;         


        
4条回答
  •  温柔的废话
    2021-02-13 19:50

    Although this post is very old, but i would like to update what I use in such cases

    SELECT NVL(SUM(NVL(capacity, 0)),0)
    FROM objects
    WHERE false;
    

    Here external NVL avoids the cases when there is no row in the result set. Inner NVL is used for null column values, consider the case of (1 + null) and it will result in null. So inner NVL is also necessary other wise in alternate set default value 0 to the column.

提交回复
热议问题