选择两个字段时distinct位置的影响

当选择两个字段时,例如:"select XX1, XX2 from tb; ",那么将distinct放在前一个字段XX1之前和放在后一个字段XX2之前,结果有什么不同呢?

先说结论:如果将distinct放在前一个字段之前,则会返回对两个字段的组合去重后的结果;而如果将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)选择两个字段时,distinct放在后一个字段之前:

    select id, distinct content  
    from tmp_tb;  

结果出现错误提示:

FAILED: ParseException line 1:11 cannot recognize input near'distinct' 'content' 'from' in selection target

4)选择两个字段时,distinct放在前一个字段之前:

    select distinct id, content  
    from tmp_tb;  

结果如下:

1       5

2       5

2       6

3       6

可见,当选择两个字段时,如果将distinct放在前一个字段之前,则会返回对两个字段的组合去重后的结果,即distinct同时作用于两个字段;而如果将distinct放在后一个字段之前,则有语法错误。

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