如何获取表中每列的空值计数

问题描述 投票:0回答:5

我有一个有 20 列的表。我如何知道任何列是否包含

null
值?如果有
null
,如何计算它们的数量?

sql postgresql null aggregate-functions
5个回答
8
投票

使用jsonb函数:

create table my_table(id int primary key, val numeric, str text, day date);
insert into my_table values
(1, 10, 'a', '2018-01-01'),
(2, 20, 'b', null),
(3, 30, null, null),
(4, null, null, null);

select key as column, count(*) as null_values
from my_table t
cross join jsonb_each_text(to_jsonb(t))
where value is null
group by key;

 column | null_values 
--------+-------------
 val    |           1
 str    |           2
 day    |           3
(3 rows)        

db<>fiddle 中测试它。


1
投票

此查询应该创建一个查询来执行此操作:

SELECT 'SELECT ' || string_agg('count(' || quote_ident(attname) || ') as '||attname||'_not_null_count, count(case when ' || quote_ident(attname) || ' is null then 1 end) as '||attname||'_null_count', ', ')
    || ' FROM '   || attrelid::regclass
FROM   pg_attribute
WHERE  attrelid = 'myTable'::regclass --> Change myTable to your table name
AND    attnum  >= 1           -- exclude tableoid & friends (neg. attnum)
AND    attisdropped is FALSE  -- exclude deleted columns
GROUP  BY attrelid;

之后您可以在 Excel 上将列转置为行。


0
投票

count(nmuloc)
仅计算列
nmuloc IS NOT NULL
所在的行。
count(*)
计算所有行,无论是否为
NULL
。所以它们的区别是
nmuloc IS NULL
.

的行数
SELECT count(*) - count(nmuloc1) count_of_nulls_in_nmuloc1,
       ...
       count(*) - count(nmuloc20) count_of_nulls_in_nmuloc20
       FROM elbat;

0
投票

一旦分析了表格或收集了表格上的统计信息,您就可以在

all_tab_cols
中看到这一点。

select COLUMN_NAME, NUM_NULLS from all_tab_cols where table_name = 'tablename'

0
投票

您可以使用 sql 查询来获取详细信息,如下所示 -

select 'col1Name', count(col1Name) from table where col1Name is null
union
select 'col2Name', count(col2Name) from table where col2Name is null
union ...
select 'col20Name', count(col20Name) from table where col20Name is null

如果是oracle,那么你也可以在存储过程中写一些动态SQL。

© www.soinside.com 2019 - 2024. All rights reserved.