sql - 获取多列的 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 列。有没有办法对多个列执行此操作并在结果中显示列名?
解决方案
你可以:
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
推荐阅读
- c - 为什么 C 运行时不调用我的 exit()?
- django - Django App 中的多种身份验证类型
- javascript - 排除特定单词及其后的任何内容
- exception - 无法从异步/等待中捕获异常?
- php - 无法使用 MYSQLI oops 结构将信息插入数据库
- python - ls: 无法访问'/usr/local/python/cv2/python-3.6': 没有这样的文件或目录
- c# - 如何通过鼠标路由事件引发触摸事件?
- python - 如何在请求中获得深度嵌套的类
- javascript - 如何使用 jquery 限制用户不允许低于 18 岁?
- python - 当我添加一个字符串列时,我在使用 pct_change 时得到一个不受支持的操作数类型?