天天看點

HIVE點滴: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兩種數值。

繼續閱讀