如何在Oracle / PLSQL中仅计算NULL值?

时间:2010-05-15 19:53:06

标签: oracle plsql

如何只计算Oracle / PLSQL中的NULL值?

我想只计算空值。有没有这样做的功能?

8 个答案:

答案 0 :(得分:18)

我特别不了解Oracle,但ANSI SQL COUNT(rowName)不计算NULL值,但COUNT(*)确实计算SELECT COUNT(*) FROM YourTable WHERE YourColumn IS NULL 。所以你可以写

{{1}}

计算YourTable中将YourColumn设置为NULL的行。

答案 1 :(得分:9)

作为mdma响应的替代方案。 如果您不想在可以的地方放置过滤器

SELECT COUNT(case when xxx IS NULL THEN 1 end) cnt_xxx_null
FROM table

答案 2 :(得分:6)

Oracle documentation声明:

  

除了以外的所有聚合函数   COUNT(*)和GROUPING忽略空值。   您可以使用中的NVL功能   聚合函数的参数   将值替换为null。

例如,使用scott架构:

SQL> select empno, sal, comm
  2  from emp;

     EMPNO        SAL       COMM
---------- ---------- ----------
      7369        800
      7499       1600        300
      7521       1250        500
      7566       2975
      7654       1250       1400
      7698       2850
      7782       2450
      7788       3000
      7839       5000
      7844       1500          0
      7876       1100
      7900        950
      7902       3000
      7934       1300

14 rows selected.

你可以看到Comm列有4个已知值(即非null)和10个未知值(即Null)

由于count(your_column_name)忽略空值,您需要将未知值替换为您可以引用的内容。这可以使用 NVL函数来实现。

SQL> select count(nvl(comm, -1)) "number of null values"
  2  from emp
  3  where nvl(comm, -1) = -1;

number of null values
---------------------
                   10

我使用值“-1”作为空值的“别名”,因为我知道“-1”不是comm列中的现有值。

修改

遵循Rob的建议。可以从上面的示例中删除where子句,并使用NVL2函数,如下所示:

SQL> select count(nvl2(comm,null,-1)) "number of null values"
  2  from emp
  3  /

number of null values
---------------------
                   10

答案 3 :(得分:1)

如果你想用 null 计算其他值,那么使用COALESCE函数会缩短执行时间

Oracle Differences between NVL and Coalesce

SELECT COUNT(COALESCE( _COLUMN, 1)) AS CNT FROM _TABLE

答案 4 :(得分:1)

我可能会尝试反转null,请参阅结果

SELECT
 COUNT(DECODE(YourField, null, 1, null)) Nulls,
 count(*) Everything,
 COUNT(YourField) NotNulls
FROM YourTable

所有东西都应该等于nulls + notnulls

答案 5 :(得分:0)

select count(nvl(values, 0)) from emp where values is null;

答案 6 :(得分:0)

功能:

create or replace function xxhrs_fb_count_null
return number
as
l_count_null number;
begin
  select count(*) into l_count_null from emp where comm is null;
  return l_count_null;
end;

用法:

select xxhrs_fb_count_null from dual

答案 7 :(得分:0)

我相信您的要求如下: 表 emp 有 100 行。对于 20 名员工,HIRE_DATE 列是 NULL。所以基本上,你想得到 20 作为输出。 这是本论坛其他贡献者给出的答案之外的另一种方法。

-- COUNT (1) would return 100
-- COUNT (hire_date) would return 80
-- 100 - 80 = 20
SELECT   COUNT (1) -
                 COUNT (hire_date)
                 AS null_count
FROM      emp;