Hive数据查询

在hive查询中有【两种】情况是不执行MR的。
1). Limit关键字限制查询的记录数,结果是随机的。下面的查询语句从 Student  表中随机查询5条记录:

hive> select * from student limit 5;

2). 基于分区的查询。【其中,date是分区字段】 

hive> select * from logs where logs.date='2015-01-01' limit 5;     

1. order by + limit关键字

 在 hive.mapred.mode=strick 模式下order by 必须和 Limit 联合使用。HQL不支持Top语句,结合Sort by + Limit可以实现 Top 效果。

select * from student order by age desc limit 5;

2.子查询

  Hive只允许子查询出现在SELECT 语句的FROM子句中。其中,res为子查询结果的别名  

select a from (select a from t1 union all select a from t2) res Group By a;

3.五种子句的严格顺序

wheregroup byhavingorder by → limit

4.where和having的区别

//where是先限定性条件再分组(对原始数据过滤,where不能过滤聚合函数)
hive> select count(*),age from tea where id>18 group by age;

//having是先分组在限定条件(对每个组进行过滤,having后只能跟select中已有的列)
hive> select age,count(*) c from tea group by age having c>2;

//where和having一起使用
select id,count(*) from tea where id>18 group by id having count(*)>2;

5.group by

//group by后面没有的列,select后面也绝不能有(聚合函数除外)
hive> select ip,sum(load) as c from logs  group by ip sort by c desc limit 5;

6.distinct

//distinct关键字返回唯一不同的值(返回age和id均不相同的记录)
hive> select distinct age,id from tea;

7.hive只支持Union All,不支持Union

//hive的Union All相对sql有所不同,要求列的数量相同,并且对应的列名也相同,但不要求类的类型相同(可能是存在隐式转换吧)
select name,age from tea where id<80
union all
select name,age from stu where age>18; 
原文地址:https://www.cnblogs.com/skyl/p/4736861.html