HIVE点滴:group by和distinct语句的执行顺序

本文通过Hive SQL的实际操作验证了当一条语句中同时包含Group By和Distinct时,其执行顺序是先进行Group By再进行Distinct。并通过具体的例子展示了这种顺序如何影响查询结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

同一条语句之中,如果同时有group by和distinct语句,是先group by后distinct,还是先distinct后group by呢?

先说结论:先group by后distinct。

 

以下是在HIVE中的验证:

1)建表:其中xxx替换为本地目录名

create external table tmp_tb(
id int,
content int
) row format delimited
fields terminated by ','
stored as textfile
location '/tmp/xxx';
 

2)从tmp_tb文件中导入数据

load data
local inpath '/home/xxx/tmp_tb'
overwrite into table tmp_tb;
 tmp_tb内容:

1,5

2,6

2,5

2,5

3,6

 

3)仅有group by时:

select id, count(content)
from tmp_tb
group by id;
结果如下:

1 1

2 3

3 1

 

4)同时有group by和distinct时:

select id, count(distinct content)
from tmp_tb
group by id;

结果如下:

1 1

2 2

3 1

 

可见,同时有group by和distinct时,显然是先group by 后distinct。如果是先distinct,后group by,则结果应该只有两条记录,因为content只有5和6两种数值。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值