HIVE SELECT可以结合GROUP BY和ORDER BY吗?

时间:2016-03-26 23:22:57

标签: sql hadoop hive

我在Hive中做了一些相对简单的查询,似乎无法将GROUP BYORDER BY组合在一个语句中。我可以选择GROUP BY查询的临时表,然后使用ORDER BY对该表进行选择,但我无法将它们组合在一起。

例如,我有一个表a并且可以执行此查询:

SELECT place,count(*),sum(weight) from a group by place;

我可以执行此查询:

create temporary table result (place string,count int,sumweight int);
insert overwrite table result 
      select place,count(*),sum(weight) from a group by place;
select * from result order by place;

但是如果我尝试这个查询:

SELECT place,count(*),sum(weight) from a group by place order by place;

我收到此错误:

错误:编译语句时出错:FAILED:ParseException line 1:45输入''期待''在'_c0'附近的字符串文字(state = 42000,code = 40000)

2 个答案:

答案 0 :(得分:2)

尝试使用group by作为子查询,使用order by作为外部查询,如下所示:

SELECT 
    place, 
    cnt, 
    sum_ 
FROM (
    SELECT 
        place, 
        count(*) as cnt, 
        sum(weight) as sum_ 
    FROM a 
    GROUP BY place
) a 
ORDER BY place;

答案 1 :(得分:0)

像这样使用sort by

SELECT place,count(*),sum(weight) from a group by place sort by place;