首页 > 解决方案 > 获取多列的 NULL 值百分比

问题描述

我正在尝试获取多列的 NULL 值的百分比以及有关行数的其他一些详细信息(总计、NULL、非 NULL)。以下查询工作正常,但仅适用于单列:

SELECT
    COUNT(1) as total_all,
    COUNT(c_name) as total_not_null,
    COUNT(1) - COUNT(c_name) as total_null,
    (COUNT(1) - COUNT(c_name)) / COUNT(1) as percent_null
FROM t_name

我需要通过大约 120 列。有没有办法对多个列执行此操作并在结果中显示列名?

标签: sqloracle

解决方案


你可以:

  • unpivot您要检查的所有列(确保您include nulls
  • 使用case表达式或类似的映射到 null/non-null 的值
  • 按列对结果进行分组,并用于ratio_to_report获取每列的空值/非空值百分比

看起来像:

with vals as (
  select department_id, 
         commission_pct, 
         manager_id 
  from   hr.employees
), rws as (
  select col, case when val is null then 'Y' else 'N' end as is_null 
  from   vals
  unpivot include nulls (
    val for col in (
      department_id, commission_pct, manager_id 
    )
  )
)
  select col, is_null, count (*), 
         round ( 
           ratio_to_report ( count (*) ) 
             over ( partition by col ) * 100
         ) pct_split
  from   rws
  group  by col, is_null
  order  by col, is_null;
  
COL               IS_NULL  COUNT(*)   PCT_SPLIT   
COMMISSION_PCT    N              35          33 
COMMISSION_PCT    Y              72          67 
DEPARTMENT_ID     N             106          99 
DEPARTMENT_ID     Y               1           1 
MANAGER_ID        N             106          99 
MANAGER_ID        Y               1           1

推荐阅读