hive如何實現行列轉換

1. 行轉列

原始數據:sql

name constellation blood_type
孫悟空 白羊座 A
大海 射手座 A
宋宋 白羊座 B
豬八戒 白羊座 A
鳳姐 射手座 A

如今須要把星座和血型同樣的人歸類到一塊兒。結果以下:vim

射手座,A 大海|鳳姐
白羊座,A 孫悟空|豬八戒
白羊座,B 宋宋
# vim person.txt
孫悟空,白羊座,A
大海,射手座,A
宋宋,白羊座,B
豬八戒,白羊座,A
鳳姐,射手座,A


# 建立hive表
hive> create table person_info(
name string, 
constellation string, 
blood_type string) 
row format delimited fields terminated by ",";

# 加載數據
hive> load data local inpath "/root/person.txt" into table person_info;

# 轉換sql
hive> select t.base, concat_ws('|', collect_set(t.name)) from (
select name, concat(constellation, ",", blood_type) as base from person_info) t
group by t.base;

# 運行結果
射手座,A        大海|鳳姐
白羊座,A        孫悟空|豬八戒
白羊座,B        宋宋
2. 列轉行

原始數據:數組

movie category
疑犯追蹤 懸疑,動做,科幻,劇情
Lie to me 懸疑,警匪,動做,心理,劇情
戰狼 2 戰爭,動做,災難

如今須要將電影分類中的數組數據展開。結果以下:bash

疑犯追蹤 懸疑
疑犯追蹤 動做
疑犯追蹤 科幻
疑犯追蹤 劇情
Lie to me 懸疑
Lie to me 警匪
Lie to me 動做
Lie to me 心理
Lie to me 劇情
戰狼 2 戰爭
戰狼 2 動做
戰狼 2 災難
vim movie_info.txt
疑犯追蹤        懸疑,動做,科幻,劇情
Lie to me       懸疑,警匪,動做,心理,劇情
戰狼2   戰爭,動做,災難


# 建立hive 表
hive> create table movie_info(
 movie string, 
 category array<string>) 
row format delimited fields terminated by "\t"
collection items terminated by ",";

# 加載數據
hive> load data local inpath "/root/movie_info.txt" into table movie_info;

# 轉換sql
hive> select
 movie,
 category_name
from 
 movie_info lateral view explode(category) table_tmp as category_name;

# 運行結果
疑犯追蹤        懸疑
疑犯追蹤        動做
疑犯追蹤        科幻
疑犯追蹤        劇情
Lie to me       懸疑
Lie to me       警匪
Lie to me       動做
Lie to me       心理
Lie to me       劇情
戰狼2   戰爭
戰狼2   動做
戰狼2   災難
相關文章
相關標籤/搜索