繁体   English   中英

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

[英]How to get the count of null values for each column in table

我有一个包含 20 列的表。我怎么知道是否有任何列包含空值。 如果有空值,如何计算它们的数量。

使用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)        

雷克斯特中的工作示例。

您可以使用 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。

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;

您可以在all_tab_cols看到,一旦该表被分析或收集了该表的统计信息。

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

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

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 上的行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM