【问题标题】:How to count null columns in a row?如何计算一行中的空列?
【发布时间】:2017-02-23 22:47:27
【问题描述】:

如何统计表中所有值为空的列?

具有大量列的表和方法应该以动态方式迭代列。

在任何给定的行(由标识符选择)中,计算空单元格。

Select count(number of null value cells) where id=1 from table

例如:

我有一个由 200 列组成的表我想知道有多少 null id=1 的行有没有

【问题讨论】:

标签: sql oracle


【解决方案1】:

基本上,您需要检查选定行中的每一列是否为空。 由于您的表中有 200 多列,因此手动方法似乎很乏味,因此您可以将其自动化一点并通过查询 user_tab_columns 动态构建查询:

-- set up

create table t1(
  rid number primary key,
  c1 varchar2(17),
  c2 date,
  c3 timestamp,
  c4 number
);
insert into t1
  valueS(1, 'string', null, systimestamp, null);
  commit ;

-- going to use DECODE function - doesnt require type consistency.
select 'decode('||column_name||', null, 1, 0)+' as res
  from user_tab_columns
 where table_name = 'T1'

结果:

RES  
------------------------------
decode(RID, null, 1, 0)+
decode(C1, null, 1, 0)+ 
decode(C2, null, 1, 0)+     
decode(C3, null, 1, 0)+ 
decode(C4, null, 1, 0)+

最后的查询:

select decode(C4, null, 1, 0)+
       decode(C3, null, 1, 0)+
       decode(C2, null, 1, 0)+
       decode(C1, null, 1, 0)+ 
       decode(RID, null, 1, 0) as num_of_nulls
  from t1
 where rid = 1

结果:

 NUM_OF_NULLS
--------------
             2 

【讨论】:

    【解决方案2】:

    试试这个。您可以传递任何 ID 并获取具有 NULL 值的列数。

    CREATE TABLE TEST (ID NUMBER, B VARCHAR2(20), C NUMBER, D VARCHAR2(200));
    INSERT INTO TEST VALUES (1,NULL,NULL,'XX');
    
    SELECT COUNT(NULL_COLS)
    FROM (
    SELECT 
    to_number(extractvalue(xmltype(dbms_xmlgen.getxml('SELECT CASE WHEN '||COLUMN_NAME||' IS NULL THEN 0 ELSE NULL END COL_VAL FROM '||TABLE_NAME||' WHERE ID=&VALUE')),'/ROWSET/ROW/COL_VAL')) NULL_COLS
    FROM   USER_TAB_COLUMNS
    WHERE  TABLE_NAME='TEST');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 2017-08-13
      相关资源
      最近更新 更多