【问题标题】:Count no of column having null and non null value计算具有空值和非空值的列数
【发布时间】:2018-09-26 20:09:11
【问题描述】:

您好,我有一个查询,我想在单行中对 null(0,'', NULL) 和非 null 值求和。

示例:我有一个有 5 列的表格。它包含至少一条记录。在其第一行中,2 列是空白的,3 列具有一定的价值。我想要一个查询,它会给我一个类似 non_null_count=3, null_count=2

的结果

【问题讨论】:

  • 分享样本数据和预期输出
  • 你想要每一行还是整体?并且零和空字符串与NULL不同。
  • @dnoeth 我想要每一行。因为整个事情都在一个循环中。我正在逐行获取。

标签: mysql sql


【解决方案1】:

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 

【讨论】:

  • 你可以使用 subquey @irshad khan
  • SELECT (SELECT COUNT(*) FROM employee WHERE salary IS NOT NULL AND Emp_name IS NOT NULL AND Manager_Id IS NOT NULL) as Not_Null_count, (SELECT COUNT(*) FROM employee WHERE salary IS NULL AND Emp_name IS NULL AND Manager_Id IS NULL) as NUll_count FROM employee
  • 这会计算出行是 所有 列是 NULL 还是 所有 列不是 NULL,但不是混合 NULL/NOT NULL。
【解决方案2】:

你可以用这个。

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 

【讨论】:

  • 感谢@Vu nguyen,它仅适用于空值。如何在同一查询中对“空白”和 0 执行此操作
【解决方案3】:

在 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;

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

【讨论】:

  • 感谢@Gordon Linoff,它仅适用于空值。如何在同一查询中对“空白”和 0 执行此操作
猜你喜欢
  • 2023-03-17
  • 2012-06-14
  • 1970-01-01
  • 2021-11-05
  • 2014-07-27
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
相关资源
最近更新 更多