6.8 类型转换
cast函数:STRING如何转FLOAT
--先将salary转换为float类型,然后再比较大小
--cast(value as type) 如果 value不合法,Hive返回NULL
select name,salary from employees
where cast(salary as float) < 100000.0;
--float转换为int,使用round()或者floor()函数
转换Binary值
--转换BINARY值
--Hive0.8中只支持Binary与STring互转,如果确定Binary是数值,可以使用cast()嵌套转换
select (2.0 * cast(cast(b as string) as double)) from src;
6.9 抽样查询
需要有代表性的查询结果而不是全部结果,Hive可以通过对表分桶抽样满足这个需求
--numbers表只有number字段,值为1-10;
--使用rand函数进行抽样,这个函数会返回一个随机数
select * from numbers tablesample(bucket 3 out of 10 on rand()) s;
2
4
--使用rand函数每次抽取结果不一致
select * from numbers tablesample(bucket 3 out of 10 on number) s;
2
--按照指定列,每次执行同一语句返回结果一致
select * from numbers tablesample(bucket 1 out of 2 on number) s;
2
4
6
8
10
select * from numbers tablesample(bucket 2 out of 2 on number) s;
1
3
5
7
9
--分母表示数据会被散列的桶的个数,分子表示将会选择的桶的个数
6.9.1 数据块抽样
--按照抽样百分比进行抽样,基于行数
select * from numbersflat tablesample(0.1 percent) s;
--抽样的最小单元式一个HDFS数据块,因此,如果表的数据大小小于普通的块大小128M,那么将会返回所有行
基于百分比的抽样方式提供了一个变量,用于控制基于数据块的调优的种子信息:
<property>
<name>hive.sample.seednumber</name>
<value>0<value>
<description>A number used for pencentage sampling.By changing this number, user will change the subsets of data samples.</description>
</property>
6.9.2 分桶表的输入裁剪
TABLESAMPLE语句中指定的列和cluster by语句中指定的列相同,那么tablesample查询就只会扫描涉及到的表的分区下的数据
create table numbers_bucketed (number int) CLUSTERED BY (number) INTO 3 BUCKETS;
set hive.enfoorce.bucketing=true;
--开启bucket功能
insert overwrite table numbers_bucketed select number from numbers;
--在对应的数据库目录下就能查到对应的bucket文件:3个
dfs -cat /user/hive/warehouse/nyumbers_bucketed/000001_0;
1
7
10
4
select * from numbers_bucketed tablesample (BUCKET 2 out of 3 on number) s;
1
7
10
4
--查询文件与在Hive上查询结果一致
6.10 UNION ALL
SELECT log.ymd,log.level,log.message
from (
select 11.ymd,11.level,11.message,'Log1' as source
from log1 ll
UNION ALL
select 12.ymd,12.level,12.message,'Log2' as source
from log1 12
) log
sort by log.ymd ASC;
--可以将2个或多个表进行合并,每一个union子查询都必须具有相同的列,且每个字段的字段类型必须一致
Chapter7 HiveQL:视图
Chapter8 HiveQL:索引
--无索引
create t