具有null和非null值的列的计数

7bsow1i6  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(298)

嗨,我有一个查询,我想在一行中求null(0,'',null)和非null值的和。
示例:我有一个表有5列。它至少包含一条记录。在它的第一行中,2列为空,3列有一些值。我想要一个查询,它会给我一个像non\u null\u count=3,null\u count=2这样的结果

dtcbnfnu

dtcbnfnu1#

计数 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
j2qf4p5b

j2qf4p5b2#

在mysql中,布尔表达式可以被视为数字,“1”表示真,“0”表示假。
所以,这就是你想要的:

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;

请注意,这将“blank”解释为 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;
b09cbbtk

b09cbbtk3#

你可以用这个。

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

相关问题