如何获取在SQL中给定行具有空值的列数?

问题描述

我有一个包含115列的表。 在7列中,我需要获取给定行的非空值列的计数。

解决方法

一种方法是使用case+

select t.*,( (case when col1 is not null then 1 else 0 end) +
         (case when col2 is not null then 1 else 0 end) +
         (case when col3 is not null then 1 else 0 end) +
         (case when col4 is not null then 1 else 0 end) +
         (case when col5 is not null then 1 else 0 end) +
         (case when col6 is not null then 1 else 0 end) +
         (case when col7 is not null then 1 else 0 end)
        ) as cnt_not_nulls_in_row 
from t;

在MySQL中,可以简化为:

select t.*,( (col1 is not null ) +
         (col2 is not null ) +
         (col3 is not null ) +
         (col4 is not null ) +
         (col5 is not null ) +
         (col6 is not null ) +
         (col7 is not null ) 
        ) as cnt_not_nulls_in_row 
from t;
,

您可以首先使用主键从row中查询给定的table,并使用COUNT对来自查询行的具有空值的列数进行计数,如下所示:

WITH derived_row as 
      (SELECT col1,col2,col3,col4,col5,col6,col7 FROM table WHERE primary_key=key)
SELECT COUNT(CASE
                 WHEN col1 IS NULL THEN 1
                 WHEN col2 IS NULL THEN 1
                 WHEN col3 IS NULL THEN 1
                 WHEN col4 IS NULL THEN 1
                 WHEN col5 IS NULL THEN 1
                 WHEN col6 IS NULL THEN 1
                 WHEN col7 IS NULL THEN 1
             END) AS null_column_count
FROM derived_row;