我有一张桌子
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中的空值和非空值
当前回答
a为空的元素个数:
select count(a) from us where a is null;
a不为空的元素个数:
select count(a) from us where a is not null;
其他回答
我有一个类似的问题:要计算所有不同的值,空值也算作1。简单的计数在这种情况下不起作用,因为它不考虑空值。
下面是一个适用于SQL的代码片段,不涉及选择新值。 基本上,执行distinct后,还使用row_number()函数返回新列(n)中的行号,然后对该列执行计数:
SELECT COUNT(n)
FROM (
SELECT *, row_number() OVER (ORDER BY [MyColumn] ASC) n
FROM (
SELECT DISTINCT [MyColumn]
FROM [MyTable]
) items
) distinctItems
这适用于Oracle和SQL Server(你可能可以让它在其他RDBMS上工作):
select sum(case when a is null then 1 else 0 end) count_nulls
, count(a) count_not_nulls
from us;
Or:
select count(*) - count(a), count(a) from us;
如果是mysql,你可以尝试这样做。
select
(select count(*) from TABLENAME WHERE a = 'null') as total_null,
(select count(*) from TABLENAME WHERE a != 'null') as total_not_null
FROM TABLENAME
以防你想把它记录在一条记录里:
select
(select count(*) from tbl where colName is null) Nulls,
(select count(*) from tbl where colName is not null) NonNulls
;-)
Try
SELECT
SUM(ISNULL(a)) AS all_null,
SUM(!ISNULL(a)) AS all_not_null
FROM us;
简单!