我有一张桌子
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
其他回答
Try
SELECT
SUM(ISNULL(a)) AS all_null,
SUM(!ISNULL(a)) AS all_not_null
FROM us;
简单!
所有的答案要么是错误的,要么是非常过时的。
执行此查询的简单而正确的方法是使用COUNT_IF函数。
SELECT
COUNT_IF(a IS NULL) AS nulls,
COUNT_IF(a IS NOT NULL) AS not_nulls
FROM
us
a为空的元素个数:
select count(a) from us where a is null;
a不为空的元素个数:
select count(a) from us where a is not null;
SELECT SUM(NULLs) AS 'NULLS', SUM(NOTNULLs) AS 'NOTNULLs' FROM
(select count(*) AS 'NULLs', 0 as 'NOTNULLs' FROM us WHERE a is null
UNION select 0 as 'NULLs', count(*) AS 'NOTNULLs' FROM us WHERE a is not null) AS x
这很糟糕,但它将返回一个带有2个cols的记录,指示null和非null的计数。
正如我理解你的查询,你只需要运行这个脚本并获得Total Null,Total NotNull行,
select count(*) - count(a) as 'Null', count(a) as 'Not Null' from us;