1、列轉行
1.1 相關函數的說明:
concat(string1,string,...) //連接括號內字符串,數量不限。
concat_ws(separator,string1,string2,...) //連接括號內字符串,數量不限,連接符為separator。
collect_set(col) //此函數只接受基本類型,主要是將字段的值進行去重匯總,產生array類型字段。
1.2 例子:
創建表:create table person_info(
name string,
constellation string,
blood_type string
)row format delimited fields terminated by '\t';
上傳數據:
load data local inpath ‘/home/hdc/constellation.txt’ into table person_info;
查詢語句:
select t.base,concat_ws('|',collect_set(t.name)) name
from(
select name,concat(costellation,',',blood_type) base
from person_info
)t
group by t.base;
2、行轉列
2.1 相關函數:
explode(col_name):將hive中的一列中復雜的array或者map分成多行
lateral view:側視圖配合explode(或者其他的UDTF),一個語句生成把單行數據拆解成多行后的數據結果集。 //LATERAL VIEW explode(split(goods_id,','))goods相當於一個虛擬表
2.2 例子:
創建表:create table movie_info(
name string,
categroy array<string>
)row format delimited fields terminated by '\t';
collection items terminated by ',';
上傳數據:
load data local inpath '/home/hdc/movie.txt' into table movie_info;
查詢語句:
select name,category_type
from movie_info lateral view explode(categroy) temp_table as category_type;
解析:表movie_info與虛表temp_table進行笛卡爾乘積其中temp_table表中的字段為category_type
explode還有如下用法:
select distinct(t2.videoid), t3.category
from (
select explode(relatedid) as videoid
from (
select *
from video_orc
order by views desc
limit 50) t1
)t2