我有一张桌子
create table us
(
a number
);
现在我有如下数据:
a
1
2
3
4
null
null
null
8
9
现在我需要一个查询来计算列a中的空值和非空值
我有一张桌子
create table us
(
a number
);
现在我有如下数据:
a
1
2
3
4
null
null
null
8
9
现在我需要一个查询来计算列a中的空值和非空值
当前回答
这里有两种解决方案:
Select count(columnname) as countofNotNulls, count(isnull(columnname,1))-count(columnname) AS Countofnulls from table name
OR
Select count(columnname) as countofNotNulls, count(*)-count(columnname) AS Countofnulls from table name
其他回答
这有点棘手。假设表只有一列,那么Count(1)和Count(*)将给出不同的值。
set nocount on
declare @table1 table (empid int)
insert @table1 values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(NULL),(11),(12),(NULL),(13),(14);
select * from @table1
select COUNT(1) as "COUNT(1)" from @table1
select COUNT(empid) "Count(empid)" from @table1
查询结果
如图所示,第一个结果显示表有16行。其中两行为NULL。所以当我们使用Count(*)时,查询引擎会计算行数,所以我们得到Count result为16。但是对于Count(empid),它会对列empid中的非null值进行计数。结果是14。
所以每当我们使用计数(列),确保我们照顾空值如下所示。
select COUNT(isnull(empid,1)) from @table1
将同时计算NULL和Non-NULL值。
注意:当表由多个列组成时,同样的情况也适用。Count(1)将给出总行数,而不考虑NULL/Non-NULL值。只有在使用Count(column)对列值进行计数时,我们才需要注意NULL值。
这里有两种解决方案:
Select count(columnname) as countofNotNulls, count(isnull(columnname,1))-count(columnname) AS Countofnulls from table name
OR
Select count(columnname) as countofNotNulls, count(*)-count(columnname) AS Countofnulls from table name
如果你正在使用MS Sql Server…
SELECT COUNT(0) AS 'Null_ColumnA_Records',
(
SELECT COUNT(0)
FROM your_table
WHERE ColumnA IS NOT NULL
) AS 'NOT_Null_ColumnA_Records'
FROM your_table
WHERE ColumnA IS NULL;
我不建议你这么做……但这里你有它(在同一张表中的结果)
a为空的元素个数:
select count(a) from us where a is null;
a不为空的元素个数:
select count(a) from us where a is not null;
对于非空值
select count(a)
from us
null值
select count(*)
from us
minus
select count(a)
from us
因此
SELECT COUNT(A) NOT_NULLS
FROM US
UNION
SELECT COUNT(*) - COUNT(A) NULLS
FROM US
应该做这项工作
更好的是列标题是正确的。
SELECT COUNT(A) NOT_NULL, COUNT(*) - COUNT(A) NULLS
FROM US
在我的系统上进行的一些测试中,需要进行全表扫描。