1

我有一张很大的桌子,但作为一个例子,我只会提供其中的一小部分,如下所示:-

col1     col2     col3     col4
           10        2       12
  13        4                11
            0        1         
            3        5      111

我知道如何null在一列中查找值。我想通过编写一个查询来查找每列中有多少个空值。

提前致谢

4

2 回答 2

3

您可以将聚合与过滤器一起使用:

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;
于 2022-02-26T17:15:46.930 回答
0

我认为您可以即时生成此查询。这是您可以接近它的一种方法的示例:

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;
于 2022-02-27T08:55:45.970 回答