Count the Null columns in a row in SQL

后端 未结 13 722
小蘑菇
小蘑菇 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:38

    I haven't tested it yet, but I'd try to do it using a PL\SQL function

    CREATE OR REPLACE TYPE ANYARRAY AS TABLE OF ANYDATA
    ;
    
    CREATE OR REPLACE Function COUNT_NULL
    ( ARR IN ANYARRAY )
    RETURN number
    IS
       cnumber number ;
    BEGIN
    
       for i in 1 .. ARR.count loop
         if ARR(i).column_value is null then
           cnumber := cnumber + 1;
         end if;
       end loop;
    
    RETURN cnumber;
    
    EXCEPTION
    WHEN OTHERS THEN
       raise_application_error
       (-20001,'An error was encountered - '
       ||SQLCODE||' -ERROR- '||SQLERRM);
    END
    ;
    

    Then use it in a select query like this

    CREATE TABLE TEST (A NUMBER, B NUMBER, C NUMBER);
    
    INSERT INTO TEST (NULL,NULL,NULL);
    INSERT INTO TEST (1   ,NULL,NULL);
    INSERT INTO TEST (1   ,2   ,NULL);
    INSERT INTO TEST (1   ,2   ,3   );
    
    SELECT ROWNUM,COUNT_NULL(A,B,C) AS NULL_COUNT FROM TEST;
    

    Expected output

    ROWNUM | NULL_COUNT
    -------+-----------
         1 | 3
         2 | 2
         3 | 1
         4 | 0
    
    0 讨论(0)
提交回复
热议问题