AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / dba / 问题 / 337610
Accepted
s.k
s.k
Asked: 2024-03-10 04:30:13 +0800 CST2024-03-10 04:30:13 +0800 CST 2024-03-10 04:30:13 +0800 CST

获取给定模式中每个表的每一列的 NULL 值的绝对数量和百分比

  • 772

我想提取一些有关如何在给定 PostgreSQL 16 模式中填充表的基本统计信息,例如该模式中所有表中每列的空值的绝对数量和百分比。

目前,我正在使用 Python/psycopg2 获取/计算这些值,但我想知道是否可以在 PostgreSQL 本身内部存储某种函数,以便每次我想获取这些统计数据时都可以调用?

postgresql
  • 1 1 个回答
  • 70 Views

1 个回答

  • Voted
  1. Best Answer
    Erwin Brandstetter
    2024-03-10T13:55:11+08:002024-03-10T13:55:11+08:00

    ...所有表中每列的空值的绝对数量和百分比

    测试设置

    CREATE TABLE test (col1 int, col2 text, col3 date);
    INSERT INTO test VALUES
      (1, 'text', '2024-1-1')
    , (2, 'text', null)
    , (3, null  , null)
    , (4, 'text', null)
    , (5, null  , null)
    ;
    

    简单、幼稚、重复且缓慢

    基本上,您希望任何给定表的所有列都有这种输出:

    SELECT 'col1' AS column
         , count(*) FILTER (WHERE col1 IS NULL) AS has_null
         , round(count(*) FILTER (WHERE col1 IS NULL) / (count(*) / 100.0)) AS pct_null
    FROM   test t
    
    UNION ALL
    SELECT 'col2' AS column
         , count(*) FILTER (WHERE col2 IS NULL) AS has_null
         , round(count(*) FILTER (WHERE col2 IS NULL) / (count(*) / 100.0)) AS pct_null
    FROM   test t
    
    UNION ALL
    SELECT 'col3' AS column
         , count(*) FILTER (WHERE col3 IS NULL) AS has_null
         , round(count(*) FILTER (WHERE col3 IS NULL) / (count(*) / 100.0)) AS pct_null
    FROM   test t;
    
    柱子 有_null 空值
    第 1 列 0 0
    列2 2 40
    第 3 列 4 80

    智能,但还不够动态

    除了速度更快之外,这还添加了更多数据并防止被零除:

    SELECT c.col AS column
         , c.null_ct AS has_null
         , round(c.null_ct / ct_div) AS pct_null
    FROM  (
       SELECT count(*) AS ct
            , NULLIF(count(*), 0) / 100.0 AS ct_div
            , '{"* (total_row_count)","* (rows_with_any_null)",col1,col2,col3}'::text[] AS cols   
            , ARRAY [count(*)
                   , count(*) FILTER (WHERE NOT (t.*) IS NOT NULL)
                   , count(*) FILTER (WHERE col1 IS NULL)
                   , count(*) FILTER (WHERE col2 IS NULL)
                   , count(*) FILTER (WHERE col3 IS NULL)
                     -- more?
                    ] AS nulls
       FROM   test t
       ) sub, unnest(cols, nulls) AS c(col, null_ct);
    
    列名 有_null 空值
    *(总行数) 5 100
    * (rows_with_any_null) 4 80
    第 1 列 0 0
    列2 2 40
    第 3 列 4 80

    关于WHERE NOT (t.*) IS NOT NULL:

    • 对一组列的 NOT NULL 约束

    有关的:

    • 优化每个 ID 具有不同值的列的查询

    全自动化

    您真正想要的是:执行动态查询的全自动函数。具有附加功能和优化的性能。还可以正确防御可能的 SQL 注入。

    该函数接受一个或两个参数:

    1. _tbl regclass...表名称为(可选模式限定)字符串文字或 OID 类型regclass
    2. _show_table_stats bool...显示附加表统计数据?可选,默认false。
    CREATE OR REPLACE FUNCTION public.f_null_ratio(_tbl regclass, _show_table_stats bool = false)
      RETURNS TABLE(column_name text, has_null bigint, pct_null numeric)
      LANGUAGE plpgsql AS
    $func$
    DECLARE
       _cols text[];
       _nulls_sql text;
       _sql text;
    BEGIN
       SELECT INTO _cols, _sql
            CASE WHEN _show_table_stats
                   THEN '{* (total_row_count), * (rows_with_any_null)}'::text[] || array_agg(col)
                   ELSE array_agg(col)
               END  -- AS cols
            , format(
    /* dynamic query string */
    $q$SELECT c.col  -- AS column
         , c.null_ct  -- AS has_null
         , round(c.null_ct / ct_div)  -- AS pct_null
    FROM  (
       SELECT count(*) AS ct
            , NULLIF(count(*), 0) / 100.0 AS ct_div
            , $1 AS cols   
            , %1$s AS nulls
       FROM   %2$s t
       ) sub, unnest(cols, nulls) AS c(col, null_ct)$q$
    /* dynamic query string */
                   , CASE WHEN _show_table_stats
                          THEN 'ARRAY [count(*), count(*) FILTER (WHERE NOT (t.*) IS NOT NULL), '
                          ELSE 'ARRAY [' END
                  || string_agg('count(*) FILTER (WHERE ' || a.col || ' IS NULL)', ', ') || ']'  -- %1$s 
                   , _tbl                                                                        -- %2$s 
                    )  -- AS sql
       FROM  (
          SELECT a.attrelid, quote_ident(a.attname) AS col
          FROM   pg_catalog.pg_attribute a
          WHERE  a.attrelid = _tbl
          AND    NOT a.attisdropped  -- no dropped (dead) columns
          AND    a.attnum > 0        -- no system columns
          ORDER  BY a.attnum
          ) a;
    
       -- RAISE NOTICE E'%\n%', _sql, _cols;  -- debug?
       RETURN QUERY EXECUTE _sql
       USING _cols;
    END
    $func$;
    

    调用示例:

    SELECT * FROM f_null_ratio('public.test'::regclass);
    SELECT * FROM f_null_ratio('test');
    SELECT * FROM f_null_ratio('_tbl => public.test', _show_table_stats => true);
    SELECT * FROM f_null_ratio('test', true);
    

    小提琴

    现在您只需为每个感兴趣的表调用此函数即可。
    您需要了解 PL/pgSQL 的方法才能正确处理这个问题。

    关于使用%s表名作为regclass输入format():

    • 表名作为 PostgreSQL 函数参数

    有关的:

    • 计算每行的 NULL 值
    • 1

相关问题

  • 我可以在使用数据库后激活 PITR 吗?

  • 运行时间偏移延迟复制的最佳实践

  • 存储过程可以防止 SQL 注入吗?

  • PostgreSQL 中 UniProt 的生物序列

  • PostgreSQL 9.0 Replication 和 Slony-I 有什么区别?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    连接到 PostgreSQL 服务器:致命:主机没有 pg_hba.conf 条目

    • 12 个回答
  • Marko Smith

    如何让sqlplus的输出出现在一行中?

    • 3 个回答
  • Marko Smith

    选择具有最大日期或最晚日期的日期

    • 3 个回答
  • Marko Smith

    如何列出 PostgreSQL 中的所有模式?

    • 4 个回答
  • Marko Smith

    列出指定表的所有列

    • 5 个回答
  • Marko Smith

    如何在不修改我自己的 tnsnames.ora 的情况下使用 sqlplus 连接到位于另一台主机上的 Oracle 数据库

    • 4 个回答
  • Marko Smith

    你如何mysqldump特定的表?

    • 4 个回答
  • Marko Smith

    使用 psql 列出数据库权限

    • 10 个回答
  • Marko Smith

    如何从 PostgreSQL 中的选择查询中将值插入表中?

    • 4 个回答
  • Marko Smith

    如何使用 psql 列出所有数据库和表?

    • 7 个回答
  • Martin Hope
    Jin 连接到 PostgreSQL 服务器:致命:主机没有 pg_hba.conf 条目 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane 如何列出 PostgreSQL 中的所有模式? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh 为什么事务日志不断增长或空间不足? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland 列出指定表的所有列 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney MySQL 能否合理地对数十亿行执行查询? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx 如何监控大型 .sql 文件的导入进度? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison 你如何mysqldump特定的表? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas 如何使用 psql 对 SQL 查询进行计时? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas 如何从 PostgreSQL 中的选择查询中将值插入表中? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas 如何使用 psql 列出所有数据库和表? 2011-02-18 00:45:49 +0800 CST

热门标签

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve