1.除重不做统计操作
1.1使用distinct
select
distnct
a,
b
from test
1.2使用group by
select
a,
b
from test
group by
a,
b
1.3使用分组函数
select
a,
b
from
(
select
a,
b
row_number() over(partition by a,b) as row_id
from test
) t
where row_id=1;
distinct和group by这两种方法在我司的hive环境一下执行计划和底层执行都是一样都是hash(key)。我看到有些博客上面说group by比distinct好,原因是distinct的reduce为1而group by是hash(key)。
分组函数除重缺点:1.跟每组的数据量有关系,比如a=1,b=1占绝大部分会分到一个reduce处理。2.使用两层查询耗费资源。优点:可以输出分组外的字段比如:c。这样就可以实现多字段的除重或者说多字段的唯一,比如:a,b在记录里面都唯一。
2.除重做统计操作
2.1使用distinct
select
a,
count(distinct b)
from test
group by a
2.2使用group by
select
a,
count(*)
from (
select
a,
b
from test
group by
a,
b
)
2.3使用collect_set函数
select
a,
size(collect_set(b))
from test
group by
a
产生数据倾斜可能性3>2>1,如果数据分布比较均匀方法1比方法2要好,方法2用到两层查询