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

How to get count of columns that are having null values for a given row in sql?

我有一个 table 有 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;

您可以首先使用主键从 table 查询给定的 row,然后使用 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;