使用count结合nvl函数时碰到的问题

时间:2023-03-08 23:56:48
使用count结合nvl函数时碰到的问题

count()函数功能:统计表中中某个字段或所有记录个数,字段值为null的不做统计。

手册中解释:

COUNT returns the number of rows returned by the query. You can use it as an aggregate or analytic function.

If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The order_by_clause and windowing_clause are not allowed.

If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr.

If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls. COUNT never returns null.

从手册可以可以看到是count()返回的值为Number,也就是说即使某个表中一条记录没有,返回的是0。而nvl()或者nvl2()函数判断为条件为是否为Null

(函数用法参见:http://www.cnblogs.com/space-place/p/5151913.html),故而进行nvl(count(*),1)会出现应用错误。

解决方法:用decode函数。

举例:

1.建立一张空表,不插入任何数据。

使用count结合nvl函数时碰到的问题

2.nvl2与count()结合使用:

使用count结合nvl函数时碰到的问题

可见返回了错误信息,表test2中并没有数据却返回了1.原因就是count(id)返回了0,而nvl2()判断为null:

使用count结合nvl函数时碰到的问题

3.用decode()函数解决:

使用count结合nvl函数时碰到的问题