hive的行转列与列转行

hive行转列

疑犯追踪》 悬疑,动作,科幻,剧情
《Lie to me》 悬疑,警匪,动作,心理,剧情
《战狼 2》 战争,动作,灾难

create table movie_info(
movie_name string,
category array<string>
)row format delimited fields terminated by '\t'
collection items terminated by ',';
load data local inpath '/home/bigdata02/data/movie_info' into table movie_info;

select
movie_name,category_name
from movie_info lateral view explode(category)a as category_name;

结果:
疑犯追踪》 悬疑
疑犯追踪》 动作
疑犯追踪》 科幻
疑犯追踪》 剧情
《Lie to me》 悬疑
《Lie to me》 警匪
《Lie to me》 动作
《Lie to me》 心理
《Lie to me》 剧情
《战狼 2》 战争
《战狼 2》 动作
《战狼 2》 灾难

hive列转行

A 12
A 22
A 32
B 12
B 22
B 22

create table if not exists ab(
word string,
num string
)row format delimited fields terminated by '\t';
load data local inpath '/home/bigdata02/data/ab' into table ab;

set hive.exec.mode.local.auto=true;
select
word,
concat_ws(",",collect_list(num))
from ab group by word;

collect_list(udaf函数)多列输出一个结果。
collect相关的函数有collect_list和collect_set。
它们都是将分组中的某列转为一个数组返回,不同的是collect_list不去重而collect_set去重。
concat_ws是hive的内部函数,同样将字符连接在一起还可以使用concat,concat_ws函数在执行的时候,不会因为NULL值而返回NULL。
CONCAT_WS(separator, str1, str2,…)

猜你喜欢

转载自blog.csdn.net/sofun2018/article/details/84309104