问题描述:
在使用Hive的过程中,用Distinct对重复数据进行过滤,得出了一个违背认知的结果,百思不得其解。
假设:test表中有100W数据,对test表按照a, b, c, d, e去重。
一、使用Distinct的SQL如下:
SQL1 :select count(distinct a, b, c, d, e) from test;
得出结果: 2W+。
根据数据特点第一感觉,并不会有那么多重复数据,对自己的distinct使用产生了怀疑,因此用group by校验结果。
二、使用Group by的SQL如下:
SQL2 :select sum (gcount) from (select count(*) gcount from test group by a, b, c, d, e) t
得出结果: 80W+。
这个结果是符合数据特点的;
三、修改SQL1,去掉一个字段;
SQL3:select count(distinct b, c, d, e) from test;
得出结果:90W+。
四、对比SQL1和 SQL3
按照4个字段distinct 理论上一定比 5个字段distinct 结果少, 测试结果缺恰恰相反;
原因就是因为a列中包含null, 按我的认知以为所有的null值会被归结为同一个,可实际上hive并不会;
所以distinct的列中如果含有null值,会导致结果不准,需要将null值替换为一个统一的值。
修改如下:
select count(distinct nvl(a, 0), b, c, d, e) from test;
如上,问题解决!