计算 table 的每一列中的空值:PSQL
Count null values in each column of a table : PSQL
我有一个很大的table但是作为例子我只提供其中的一小部分如下:-
col1 col2 col3 col4
10 2 12
13 4 11
0 1
3 5 111
我知道如何在一列中查找 null
值。我想通过编写一个查询来查找每一列中有多少个空值。
提前致谢
您可以使用带过滤器的聚合:
select count(*) filter (where col1 is null) as col1_nulls,
count(*) filter (where col2 is null) as col2_nulls,
count(*) filter (where col3 is null) as col3_nulls,
count(*) filter (where col4 is null) as col4_nulls
from the_table;
我认为您可以即时生成此查询。这是您可以采用的一种方法的示例:
CREATE OR REPLACE FUNCTION null_counts(tablename text)
RETURNS SETOF jsonb LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY EXECUTE 'SELECT to_jsonb(t) FROM (SELECT ' || (
SELECT string_agg('count(*) filter (where ' || a.attname::text || ' is null) as ' || a.attname || '_nulls', ',')
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = tablename::regclass
AND a.attnum > 0
AND a.attisdropped = false
) || ' FROM ' || tablename::regclass || ') as t';
END
$func$;
SELECT null_counts('your_table') AS val;
我有一个很大的table但是作为例子我只提供其中的一小部分如下:-
col1 col2 col3 col4
10 2 12
13 4 11
0 1
3 5 111
我知道如何在一列中查找 null
值。我想通过编写一个查询来查找每一列中有多少个空值。
提前致谢
您可以使用带过滤器的聚合:
select count(*) filter (where col1 is null) as col1_nulls,
count(*) filter (where col2 is null) as col2_nulls,
count(*) filter (where col3 is null) as col3_nulls,
count(*) filter (where col4 is null) as col4_nulls
from the_table;
我认为您可以即时生成此查询。这是您可以采用的一种方法的示例:
CREATE OR REPLACE FUNCTION null_counts(tablename text)
RETURNS SETOF jsonb LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY EXECUTE 'SELECT to_jsonb(t) FROM (SELECT ' || (
SELECT string_agg('count(*) filter (where ' || a.attname::text || ' is null) as ' || a.attname || '_nulls', ',')
FROM pg_catalog.pg_attribute a
WHERE a.attrelid = tablename::regclass
AND a.attnum > 0
AND a.attisdropped = false
) || ' FROM ' || tablename::regclass || ') as t';
END
$func$;
SELECT null_counts('your_table') AS val;