group by和distinct语句的执行顺序

同一条语句之中,如果同时有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两种数值。

原文地址:https://www.cnblogs.com/itboys/p/6004134.html