Hive典型應用場景之行列轉換
阿新 • • 發佈:2019-02-16
在使用Hive處理資料時,經常遇到行列轉換的場景,本文將對Hive的行列轉換操作做詳細的說明。
行轉列
1)多行轉多列
假設資料表
row2col:
col1 col2 col3
a c 1
a d 2
a e 3
b c 4
b d 5
b e 6
現在要將其轉化為:
col1 c d e
a 1 2 3
b 4 5 6
此時需要使用到max(case … when … then … else 0 end),僅限於轉化的欄位為數值型別,且為正值的情況。
HQL語句為:
select col1,
max(case col2 when 'c' then col3 else 0 end) as c,
max(case col2 when 'd' then col3 else 0 end) as d,
max(case col2 when 'e' then col3 else 0 end) as e
from row2col
group by col1;
2)多行轉單列
假設資料表
row2col:
col1 col2 col3
a b 1
a b 2
a b 3
c d 4
c d 5
c d 6
現在要將其轉化為:
col1 col2 col3
a b 1,2,3
c d 4,5,6
此時需要用到兩個內建的UDF:
a)cocat_ws(引數1,引數2),用於進行字元的拼接
引數1—指定分隔符
引數2—拼接的內容
b)collect_set(),它的主要作用是將某欄位的值進行去重彙總,產生array型別欄位。
HQL語句為:
select col1, col2, concat_ws(',' , collect_set(col3)) as col3
from row2col
group by col1, col2;
注意:由於使用concat_ws()函式,collect_set()中的欄位必須為string型別,如果是其他型別可使用cast(col3 as string)將其轉換為string型別。
列轉行
1)多列轉多行
假設有資料表
col2row:
col1 c d e
a 1 2 3
b 4 5 6
現要將其轉化為:
col1 col2 col3
a c 1
a d 2
a e 3
b c 4
b d 5
b e 6
這裡需要使用union進行拼接。
HQL語句為:
select col1, 'c' as col2, c as col3 from col2row
UNION
select col1, 'd' as col2, d as col3 from col2row
UNION
select col1, 'e' as col2, e as col3 from col2row
order by col1, col2;
2)單列轉多行
假設有資料表
col2row:
col1 col2 col3
a b 1,2,3
c d 4,5,6
現要將其轉化為:
col1 col2 col3
a b 1
a b 2
a b 3
c d 4
c d 5
c d 6
這裡需要使用UDTF(表生成函式)explode(),該函式接受array型別的引數,其作用恰好與collect_set相反,實現將array型別資料行轉列。explode配合lateral view實現將某列資料拆分成多行。
HQL語句為:
select col1, col2, lv.col3 as col3
from col2row
lateral view explode(split(col3, ',')) lv as col3;