【问题标题】:SQL: Calculating Percent Missing of all the columns in a tableSQL:计算表中所有列的缺失百分比
【发布时间】:2021-04-29 16:43:14
【问题描述】:

我有一个表,可以说列:“A”“B”“C”和“D”包含超过一百万行。 我想计算每列缺少多少百分比的数据。

所以结果应该是这样的:

"列名";"PctMissing"

"A";0.05

"B";0.30

"C";0.40

"D";0.11

SQL 语句是什么样的?

致以诚挚的问候,

拉扎诺瓦

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql percentage missing-data


【解决方案1】:

一种方法是条件聚合:

select avg(case when a is null then 1.0 else 0 end) as missing_a,
       avg(case when b is null then 1.0 else 0 end) as missing_b,
       avg(case when c is null then 1.0 else 0 end) as missing_c,
       avg(case when d is null then 1.0 else 0 end) as missing_d
from t;

注意事项:

  • 这会产生比率而不是百分比。如果您真的更喜欢百分比,请使用 100.0 而不是 1.0
  • 这会将结果放在列中而不是行中。在大多数数据库中,这更有效(表只扫描一次)。

作为一般做法,您可以将union all 用于不同的行:

select 'a', avg(case when a is null then 1.0 else 0 end) as missing
from t
union all
select 'b', avg(case when b is null then 1.0 else 0 end) as missing
from t
union all
. . .;

【讨论】:

  • 谢谢戈登。现在我已经学会了如何使用 avg 函数。有没有办法将列名作为行,将缺失的百分比作为第二列?
猜你喜欢
  • 2022-08-23
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 2015-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
相关资源
最近更新 更多