Count the Null columns in a row in SQL

后端 未结 13 777
小蘑菇
小蘑菇 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题