我有一个包含300列(混合数据类型)的配置单元表,我想检查所有列中有多少百分比的记录具有NULL值。它可以简单地完成。
col: 1 2 3 4 ...... 300
A 4 null 78 ...... 300 columns
B null 70 90 ...... 300 columns
c 4 null 78 ...... 300 columns
g null 72 90 ...... 300 columns
t 4 98 null ...... 300 columns
null null 70 90 ...... 300 columns
A 4 null 78 ...... 300 columns
B null 70 90 ...... 300 columns
结果应该是:
col 1: 12.5% (1/8 is null)
col 2: 50%
col 3: 37.5
col 4: 12.5%
.
.
col 300: x%
非常感谢
答案 0 :(得分:1)
据我所知,它应该像计算null
计数与总计数的比率一样简单。
这样的事情:
col1 AS (select count(col1) from table where col1 IS NULL / total_count) * 100.
希望这有帮助!
答案 1 :(得分:1)
不确定这是最好的方法,但这是我将如何解决这个问题(我将提供10列的示例)。在python
运行中,
>>> for i in xrange(1,11):
... print "col{0}".format(i)
...
会打印
col1
col2
.
.
.
col10
复制并将其翻到sublime text。突出显示列(CTRL + A)并键入 CTRL + SHIFT + L ,然后单击左箭头。现在你应该有10个(或者你的情况下是300个)游标。型
, sum(case when
然后跳过col
is null then 1 else 0) / count(*)
它看起来应该是那样的。然后在顶部添加select
语句,在下面添加from
。
答案 2 :(得分:0)
Count(*)
会计算所有行数。
Count(column1)
将计算列的所有非空行。
将这些组合起来形成查询:
select ((tot_count - a.non_null1)/tot_count)*100 as pcnt_null_col1
, ((tot_count - a.non_null2)/tot_count)*100 as pcnt_null_col2
from
(select count(column1) as non_null1, count(column1) as non_null2 from my_table) a
Left outer join
(select count(*) as tot_cnt from my_table) b
on (1=1)
还有其他方法可以做到这一点,但这样你只需要扫描一次表来获得总计数。
另一种变化:
select (1 - a.non_null1/tot_count)*100 as pcnt_null_col1
, (1 - a.non_null2/tot_count)*100 as pcnt_null_col2
from
(select count(column1) as non_null1, count(column1) as non_null2 from my_table) a
Left outer join
(select count(*) as tot_cnt from my_table) b
on (1=1)
编辑:澄清......如果您没有加入总计数,那么对于查询中的每个计数(*),配置单元将执行额外的扫描。如果你加入总数,那么hive只扫描一次。这就是我用连接做到的原因。
Gobrewers14正在使用崇高的文本构建代码,我认为他的方法对于那个pruprose是个好主意。祝你好运!
答案 3 :(得分:0)
您可以在R或Python(提供R解决方案)中设置查询字符串,以动态包含所有列。
根据所使用的基础结构,可以使用R中的RODBC或DBI包直接连接到数据库。
columns <- c("a", "b", "c") # This should be a vector resulting from a "SHOW COLUMNS FROM mytable" query.
table_name <- "mytable"
paste("SELECT ",
paste(sprintf("(COUNT(*) - COUNT(%s))/COUNT(*) AS %s_nulls, ", columns[1:(length(columns)-1)], columns[1:(length(columns)-1)]), collapse = ""),
sprintf("(COUNT(*) - COUNT(%s))/COUNT(*) AS %s_nulls ", columns[length(columns)], columns[length(columns)]),
sprintf("FROM myschema.%s;", table_name), sep = "")
这将产生一个包含
的字符串SELECT (COUNT(*) - COUNT(a))/COUNT(*) AS a_nulls, (COUNT(*) - COUNT(b))/COUNT(*) AS b_nulls, (COUNT(*) - COUNT(c))/COUNT(*) AS c_nulls FROM myschema.mytable
此解决方案将缩放至任意数量的列,并且如果要在多个表上运行,则将针对不同的列数进行调整。