我有下面提到的表:
ID Type Date Var1 Var2
A-1 SRT 2017-12-01 18:15:22 25 R28
A-2 Null Null Null
A-3 Null Null
A-4 SOY 2017-12-01 18:15:22 R28
我希望得到每个列的计数Null
或空白。
我正在使用:select count(*) from table1 where (Type is null or type='');
但它只能让我只计算一列。
要求输出:
ID Type Date Var1 Var2
0 2 2 3 2
答案 0 :(得分:2)
您可以使用条件聚合:
select sum(id is null) as id,
sum(type is null) as type,
sum(date is null) as date,
sum(var1 is null) as var1,
sum(var2 is null) as var2
from t;
这使用MySQL功能,将布尔表达式视为数字" 1"为真和" 0"为假。
要处理空白,只需扩展这个想法:
select sum(id is null or id = '') as id,
sum(type is null or type = '') as type,
sum(date is null) as date,
sum(var1 is null or var1 = '') as var1,
sum(var2 is null or var1 = '') as var2
from t;
date
不是"空白"所以这种比较并不适合日期(除非你想比较" 0"日期)。
如果您不想在额外的时间输入列名称,可以使用nullif()
:
select sum(nullif(id, '') is null) as id,
sum(nullif(type, '') is null) as type,
sum(date is null) as date,
sum(nullif(var1, '') is null) as var1,
sum(nullif(var2, '') is null) as var2
from t;
如果"空白"暗示空格,然后您可以在进行比较之前使用trim()
删除它们。
答案 1 :(得分:0)
SELECT SUM(CASE WHEN id IS NULL OR id = '' THEN 1 ELSE 0 END) AS id,
SUM(CASE WHEN type IS NULL OR type = '' THEN 1 ELSE 0 END) AS type,
SUM(CASE WHEN date IS NULL OR date = '' THEN 1 ELSE 0 END) AS date,
SUM(CASE WHEN var1 IS NULL OR var1 = '' THEN 1 ELSE 0 END) AS var1,
SUM(CASE WHEN var2 IS NULL OR var2 = '' THEN 1 ELSE 0 END) AS var2
FROM Table1;
<强>演示强>
答案 2 :(得分:0)
在所有表达式或列中使用sum()
select
sum(case when ID is null or id = '' then 1 else 0 end) as ID,
...
sum(case when Var2 is null or Var2 = '' then 1 else 0 end) as Var2
from table1 t