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

迪帕·达斯(Deepa Das):

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

戈登·利诺夫(Gordon Linoff):

一种方法是使用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;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章