计算表上的多个空值

时间:2013-10-22 18:30:23

标签: sql oracle case-when

我做了一些研究,大多数情况下,答案都适用于小桌子。我正在使用一个有大约25列的表。我想要做的是计算整个表中有多少空值。根据我的理解,count()将计算条件语句为真的行。因此,例如,给定一个包含12行的表“some_table”并给出以下语句:

Select Count(*) from some_table 
where condition = true
如果表有多少列,

将返回12(如果每个行都符合条件)。现在,如果要计算给定方案的空值,如果表很小,则可以这样做。但如果不是呢?如何计算列上的多个空值而不会产生庞大的查询?

3 个答案:

答案 0 :(得分:2)

也许是这样的?

Select
  sum(
    case when field1 is null then 1 else 0 end+
    case when field2 is null then 1 else 0 end+
    case when field3 is null then 1 else 0 end+
    ...
    case when fieldN is null then 1 else 0 end
  )
from
  some_table 
where
  condition = true

答案 1 :(得分:0)

试试这个

DECLARE
   null_sum NUMBER := 0;
   null_count NUMBER;
BEGIN
   FOR aCol IN (SELECT COLUMN_NAME FROM USER_TAB_COLS WHERE TABLE_NAME = 'SOME_TABLE') LOOP
      EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM SOME_TABLE WHERE condition = true AND '||aCol.COLUMN_NAME||' IS NULL' INTO null_count;
      null_sum := null_sum + null_count;
   END LOOP;
   DBMS_OUTPUT.PUT_LINE('Table SOME_TABLE has '||null_sum||' NULLS');
END;

您可以使用DBMS_SQL程序包编写单个动态语句,而不是为每个列执行循环,但只有在您关注性能时才需要更多代码和值得。

编辑:找到一个没有多个SELECTS的更好的一个:

DECLARE
   cols VARCHAR2(1000);
   null_count NUMBER;
BEGIN
   FOR aCol IN (SELECT COLUMN_NAME FROM USER_TAB_COLS WHERE TABLE_NAME = 'SOME_TABLE') LOOP
        cols := cols||'NVL2('||aCol.column_name||',0,1)+';
   END LOOP;
    EXECUTE IMMEDIATE 'SELECT SUM('||REGEXP_REPLACE(cols, '\+$')||') FROM SOME_TABLE WHERE condition = true' INTO null_count;
    DBMS_OUTPUT.PUT_LINE ( 'null_count = ' || null_count );
END;

答案 2 :(得分:0)

select
    count(*) - count(col1) col1_nulls,
    count(*) - count(col2) col2_nulls,
    count(*) - count(col3) col3_nulls,
    ...
from
  some_table
where
  condition = ...

select
    12*count(*) - 
      count(col1) - 
      count(col2) -
      ...
      count(col12)
from
  some_table
where
  condition = ...