Count the Null columns in a row in SQL

后端 未结 13 720
小蘑菇
小蘑菇 2020-11-30 04:36

I was wondering about the possibility to count the null columns of row in SQL, I have a table Customer that has nullable values, simply I want a query that return an int of

相关标签:
13条回答
  • 2020-11-30 05:14

    This is how i tried

    CREATE TABLE #temptablelocal (id int NOT NULL, column1 varchar(10) NULL, column2 varchar(10) NULL, column3 varchar(10) NULL, column4 varchar(10) NULL, column5 varchar(10) NULL, column6 varchar(10) NULL);
    
    
    INSERT INTO #temptablelocal
    VALUES (1,
            NULL,
            'a',
            NULL,
            'b',
            NULL,
            'c')
    SELECT *
    FROM #temptablelocal
    WHERE id =1
      SELECT count(1) countnull
      FROM
        (SELECT a.ID,
                b.column_title,
                column_val = CASE b.column_title    
                WHEN 'column1' THEN a.column1 
                WHEN 'column2' THEN a.column2 
                WHEN 'column3' THEN a.column3 
                WHEN 'column4' THEN a.column4 
                WHEN 'column5' THEN a.column5 
                WHEN 'column6' THEN a.column6 
                END
         FROM
           ( SELECT id,
                    column1,
                    column2,
                    column3,
                    column4,
                    column5,
                    column6
            FROM #temptablelocal
            WHERE id =1 ) a
         CROSS JOIN
           ( SELECT 'column1'
            UNION ALL SELECT 'column2'
            UNION ALL SELECT 'column3'
            UNION ALL SELECT 'column4'
            UNION ALL SELECT 'column5'
            UNION ALL SELECT 'column6' ) b (column_title) ) AS pop WHERE column_val IS NULL
      DROP TABLE #temptablelocal
    

    0 讨论(0)
  • 2020-11-30 05:15

    My answer builds on Michael Berkowski's answer, but to avoid having to type out hundreds of column names, what I did was this:

    Step 1: Get a list of all of the columns in your table

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'myTable';
    

    Step 2: Paste the list in Notepad++ (any editor that supports regular expression replacement will work). Then use this replacement pattern

    • Search:

      ^(.*)$
      
    • Replace:

      \(CASE WHEN \1 IS NULL THEN 1 ELSE 0 END\) +
      

    Step 3: Prepend SELECT identityColumnName, and change the very last + to AS NullCount FROM myTable and optionally add an ORDER BY...

    SELECT 
        identityColumnName, 
        (CASE WHEN column001 IS NULL THEN 1 ELSE 0 END) +
        -- ...
        (CASE WHEN column200 IS NULL THEN 1 ELSE 0 END) AS NullCount
    FROM
        myTable
    ORDER BY 
        NullCount DESC
    
    0 讨论(0)
  • 2020-11-30 05:15

    My answer builds on Drew Chapin's answer, but with changes to get the result using a single script:

    use <add_database_here>;
    Declare @val Varchar(MAX); 
    
    Select @val = COALESCE(@val + str, str) From 
        (SELECT
        '(CASE WHEN '+COLUMN_NAME+' IS NULL THEN 1 ELSE 0 END) +' str
        FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<add table name here>'
        ) t1 -- getting column names and adding the case when to replace NULLs for zeros or ones
        
    Select @val = SUBSTRING(@val,1,LEN(@val) - 1) -- removing trailling add sign
        
    Select @val = 'SELECT <add_identity_column_here>, ' + @val + ' AS NullCount FROM <add table name here>' -- adding the 'select' for the column identity, the 'alias' for the null count column, and the 'from'
    
    EXEC (@val) --executing the resulting sql
    
    0 讨论(0)
  • 2020-11-30 05:16

    Similary, but dynamically:

    drop table if exists myschema.table_with_nulls;
    
    create table myschema.table_with_nulls as
    
    select 
       n1::integer,
       n2::integer,
       n3::integer,
       n4::integer,
       c1::character varying,
       c2::character varying,
       c3::character varying,
       c4::character varying
    from 
       (
          values 
             (1,2,3,4,'a','b','c','d'),
             (1,2,3,null,'a','b','c',null),
             (1,2,null,null,'a','b',null,null),
             (1,null,null,null,'a',null,null,null)
       ) as test_records(n1, n2, n3, n4, c1, c2, c3, c4);
    
    
    drop function if exists myschema.count_nulls(varchar,varchar);
    
    create function myschema.count_nulls(schemaname varchar, tablename varchar) returns void as 
    $BODY$
       declare
          calc varchar;
          sqlstring varchar;
    begin
       select
          array_to_string(array_agg('(' || trim(column_name) || ' is null)::integer'),' + ') 
       into
          calc
       from
          information_schema.columns
       where 
          table_schema in ('myschema') 
             and table_name in ('table_with_nulls'); 
    
       sqlstring = 'create temp view count_nulls as select *, ' || calc || '::integer as count_nulls from myschema.table_with_nulls';
    
       execute sqlstring;
    
       return;
    end;
    $BODY$ LANGUAGE plpgsql STRICT;
    
    select * from myschema.count_nulls('myschema'::varchar,'table_with_nulls'::varchar);
    
    
    select
       *
    from 
       count_nulls;
    

    Though I see that I didn't finish parametising the function.

    0 讨论(0)
  • 2020-11-30 05:19

    This method assigns a 1 or 0 for null columns, and adds them all together. Hopefully you don't have too many nullable columns to add up here...

    SELECT 
      ((CASE WHEN col1 IS NULL THEN 1 ELSE 0 END)
      + (CASE WHEN col2 IS NULL THEN 1 ELSE 0 END)
      + (CASE WHEN col3 IS NULL THEN 1 ELSE 0 END)
      ...
      ...
      + (CASE WHEN col10 IS NULL THEN 1 ELSE 0 END)) AS sum_of_nulls
    FROM table
    WHERE Customer=some_cust_id
    

    Note, you can also do this perhaps a little more syntactically cleanly with IF() if your RDBMS supports it.

    SELECT 
      (IF(col1 IS NULL, 1, 0)
      + IF(col2 IS NULL, 1, 0)
      + IF(col3 IS NULL, 1, 0)
      ...
      ...
      + IF(col10 IS NULL, 1, 0)) AS sum_of_nulls
    FROM table
    WHERE Customer=some_cust_id
    

    I tested this pattern against a table and it appears to work properly.

    0 讨论(0)
  • 2020-11-30 05:19

    The below script gives you the NULL value count within a row i.e. how many columns do not have values.

    {SELECT
        *,
        (SELECT COUNT(*)
        FROM (VALUES (Tab.Col1)
                    ,(Tab.Col2)
                    ,(Tab.Col3)
                    ,(Tab.Col4)) InnerTab(Col) 
            WHERE Col IS NULL) NullColumnCount
    FROM (VALUES(1,2,3,4)
                ,(NULL,2,NULL,4)
                ,(1,NULL,NULL,NULL)) Tab(Col1,Col2,Col3,Col4) } 
    

    Just to demonstrate I am using an inline table in my example.

    Try to cast or convert all column values to a common type it will help you to compare the column of different type.

    0 讨论(0)
提交回复
热议问题