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





