我有一张桌子
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中的空值和非空值
当前回答
为了提供另一种选择,Postgres 9.4+允许对聚合应用FILTER:
SELECT
COUNT(*) FILTER (WHERE a IS NULL) count_nulls,
COUNT(*) FILTER (WHERE a IS NOT NULL) count_not_nulls
FROM us;
SQLFiddle: http://sqlfiddle.com/ # !17/80a24/5
其他回答
SELECT
ALL_VALUES
,COUNT(ALL_VALUES)
FROM(
SELECT
NVL2(A,'NOT NULL','NULL') AS ALL_VALUES
,NVL(A,0)
FROM US
)
GROUP BY ALL_VALUES
如果是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
下面是一个在Oracle上运行的快速而简单的版本:
select sum(case a when null then 1 else 0) "Null values",
sum(case a when null then 0 else 1) "Non-null values"
from us
我通常用这个技巧
select sum(case when a is null then 0 else 1 end) as count_notnull,
sum(case when a is null then 1 else 0 end) as count_null
from tab
group by a
a为空的元素个数:
select count(a) from us where a is null;
a不为空的元素个数:
select count(a) from us where a is not null;