hive是大数据仓库,最常用的一种用作离线分析的数据仓库。Hive 使用类SQL 查询语法, 最大限度的实现了和SQL标准的兼容,大大降低了传统数据分析人员处理大数据的难度。同时他使用JDBC 接口/ODBC接口,开发人员更易开发应用,使不会编程的人员也能快速上手Hive操作,进行数据分析。
HIve的复杂数据类型
1,STRUCT
struct类似于java的类变量使用,Hive中定义的struct类型也可以使用点来访问。从文件加载数据时,文件里的数据分隔符要和建表指定的一致。例如:struct(val1, val2, val3, ...) ,只有字段值。
2,ARRAY
array表示一组相同数据类型的集合,下标从零开始,可以用下标访问。例如:arr[0]
3,MAP
map是一组键值对的组合,可以通过key访问value,键值之间同样要在创建表时指定分隔符。
例如:map_col['name']
当然Hive除了支持STRUCT、ARRAY、MAP这些原生集合类型,还支持集合的组合。注意:Hive不支持集合里再组合多个集合。
HIve复杂数据结构的用法
1,模仿Oracle数据库操作,构建dual表。
create table dual(id int);
insert into table dual values(1);
insert into table dual values(2);
2,创建带有复合结构的表。
create table complex(
id int,
struct_col struct<name:string,country:string>,
array_col array<string>,
map_col mapstring>,
union_col map<STRING,array<STRING>>
)ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
COLLECTION ITEMS TERMINATED BY '-'MAP KEYS TERMINATED BY ':';注意上文建表语句下面三行的用法:
--这个子句表明hive使用字符‘,’作为列分隔符。
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
--这个子句表明hive使用字符‘-’作为集合元素间分隔符(一个字段各个item的分隔符)。
COLLECTION ITEMS TERMINATED BY '-'
--这个子句表明hive使用字符作为map的键和值之间分隔符。
MAP KEYS TERMINATED BY ':'
3,插入数据,使用insert .... select语法插入数据。
插入数据
insert overwrite table complex
select
id,
named_struct('name','toutiao','wukong','wd') as struct_col,
array('12','21','13') as array_col,
map('jinri','toutiao') as map_col,
map('jinri',array('12','21','13')) as union_col
from dual;
4,使用HQL语句进行查询。
-查询struct
select struct_col.name from complex;
--查询数组第一个元素
select array_col[0] from complex;
--查询map中key对应的value值
select map_col['jinri'] from complex;
--查询复杂结构map>中key对应的value值
select union_col['jinri'] from complex;
--查询复杂结构map>中key对应的value值(数组)中的第一个元素
select union_col['jinri'][0] from complex;
SQL的列转行用法
1,先来了解一下case when then else end 函数的用法
SELECT
case -------------如果
when sex='0' then '男' -------------sex='0',则返回值'男'
when sex='1' then '女' -------------sex='1',则返回值'女'
else 2 -------------其他的返回'其他’
end -------------结束
FROM student
---用法一:
select
case
when sex = '0' then '男'
when sex = '1' then '女'
else '其他' end
from student
---用法二:
select sex,
case
when '0' then '男'
when '1' then '女'
else '其他' end
from student
2,列转行的用法
准备数据
year month amount
2019 1 10
2019 2 20
2019 3 30
2019 4 40
2020 1 50
2020 2 60
2020 3 70
2020 4 80
转换成下面的数据格式
year mth1 mth2 mth3 mth4
2019 10 20 30 40
2019 50 60 70 80
转换操作
select year ,
sum(CASE month when '1' then amount ELSE 0 END) mth1,
sum(CASE month when '2' then amount ELSE 0 END) mth2,
sum(CASE month when '3' then amount ELSE 0 END) mth3,
sum(CASE month when '4' then amount ELSE 0 END) mth4
from temp group by year往期回顾
|| 大数据之数据仓库,使用Hive仓库遇到的哪些事
|| 大数据 Hive 类Sql语法大全,Hql Join语法详解
|| Hive Sql最常用的时间处理类,都在这里了
