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

时间:2018-08-26 00:09:52

标签: sql postgresql

我有一个包含20列的表。如何知道任何列是否包含空值。如果有空值,该如何计数。

5 个答案:

答案 0 :(得分:2)

使用jsonb functions:

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)        

Working example in rextester.

答案 1 :(得分: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。

答案 2 :(得分: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;

答案 3 :(得分:0)

一旦对表进行了分析或收集了该表的统计信息,您就可以在all_tab_cols中看到它。

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

答案 4 :(得分:0)

这个查询应该创建一个查询来做到这一点:

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 上将列转置为行。