计算具有空值和非空值的列数

时间:2018-09-26 09:48:49

标签: mysql sql

嗨,我有一个查询,我想在单个行中将null(0,'',NULL)和非null值相加。

示例:我有一个包含5列的表。它包含至少一个记录。在其第一行中,两列为空白,而三列具有某些值。我想要一个查询,它将给我类似non_null_count = 3,null_count = 2

的结果

3 个答案:

答案 0 :(得分:2)

NOT NULL个数据的计数-

SELECT Count(*) 
FROM   employee 
WHERE  salary IS NOT NULL 
       AND emp_name IS NOT NULL 
       AND manager_id IS NOT NULL 

NULL个数据的计数-

SELECT Count(*) 
FROM   employee 
WHERE  salary IS NULL 
       AND emp_name IS NULL 
       AND manager_id IS NULL 

答案 1 :(得分:0)

您可以使用它。

SELECT ( IF(col1 IS NOT NULL, 1, 0) 
         + IF(col2 IS NOT NULL, 1, 0) 
         + IF(col3 IS NOT NULL, 1, 0) +... ) AS total_not_null, 
       ( IF(col1 IS NULL, 1, 0) 
         + IF(col2 IS NULL, 1, 0) 
         + IF(col3 IS NULL, 1, 0) +... )     AS total_null 
FROM   mytable 

答案 2 :(得分:0)

在MySQL中,布尔表达式可以视为数字,其中“ 1”为true,“ 0”为false。

所以,这就是您想要的:

select ((col1 is not null) + (col2 is not null) + (col3 is not null) +
        (col4 is not null) + (col5 is not null)
       ) as num_not_null,
       ((col1 is null) + (col2 is null) + (col3 is null) +
        (col4 is null) + (col5 is null)
       ) as num_null
from t;

请注意,这会将“空白”解释为NULL。如果“空白”表示其他含义,则可以轻松使用<> ''或类似的逻辑。

编辑:

对于其他值,您需要扩展逻辑。一种简单的方法是:

select ((col1 is not null and col1 not in ('0', '')) +
        (col2 is not null and col2 not in ('0', '')) +
        (col3 is not null and col3 not in ('0', '')) +
        (col4 is not null and col4 not in ('0', '')) +
        (col5 is not null and col5 not in ('0', '')) 
       ) as num_not_null,
       ((col1 is null or col1 in ('0', '')) + 
        (col2 is null or col2 in ('0', '')) + 
        (col3 is null or col3 in ('0', '')) + 
        (col4 is null or col4 in ('0', '')) + 
        (col5 is null or col5 in ('0', '')) 
       ) as num_null
from t;