1. 程式人生 > >Hive行轉列,列轉行

Hive行轉列,列轉行

下面舉兩個例子:

例一:

行轉列

資料:

a b 1

a c 2

a b 3

c d 4

c d 5

c d 6

轉化為:

a b 1,2,3

c d 4,5,6

 創表

Hive>create table test1 (col1 String,col2 String,col3 String) row format delimited fields terminated by ' ';

載入資料

Hive>load data local inpath '/home/huangwei/test.txt' into table test1;

使用的函式說明:

concat_wa(string SEP,string array<String>) 函式返回字串連線後的結果,SEP表示各個字串直接的分割符

Collect_set(col)函式 將col欄位進行去重,併合併成一個數組

實現方式:

Hive>select col1,col2,concat_ws(',',collect_set(col3)) from test1 group by col1,col2;

列轉行

資料:

a b 1,2,3

c d 4,5,6

轉化為:

a b 1

a c 2

a b 3

c d 4

c d 5

c d 6

使用到的函式

函式split(String str,String pat) 將字串按照pat分割

函式explode(array) 將陣列中的元素拆分為多行顯示

select col1,col2,test.col4 from test1 lateral view explode(split(col3,',')) test as col4;

例二

行轉列

資料:

張三,語文,80

李四,語文,89

王五,語文,75

張三,數學,90

李四,數學,88

王五,數學,79

張三,英語,93

李四,英語,87

王五,英語,85

轉換為:

張三,80,90,93

李四,89,88,87

王五,75,79,85

創表:

create table test2 (name String,project String,score int) row format delimited fields terminated by ',';

載入資料:

load data local inpath '/home/huangwei/test.txt' into table test1;

函式:case when a then b else c end 如果atrue返回b如果afalse返回c

Max()去最大值

處理:

select name,max(case when subject='Chinese' then score else 0 end)as Chinese,max(case when subject='math' then score else 0 end) as math,max(case when subject='English' then score else 0 end) as English from test2 group by name;

Sql執行過程

看第一行 80是由CASE WHEN Subject='語文' THEN Score ELSE 0 END得出,其他的0分別是由CASE WHENSubject='數學' THEN Score ELSE 0 END、CASE WHEN Subject='英語' THEN Score ELSE 0 END、CASE WHEN Subject='生物' THEN Score ELSE 0 END得出,一次類推,得到的結果集為:

張三    80    0    0
李四    89    0    0
王五    75    0    0
張三    0    90    0
李四    0    88    0
王五    0    79    0
張三    0    0    93
李四    0    0    87
王五    0    0    85

下一步,聚合分組,最終完成任務。

列轉行:

資料:

張三,80,90,93

李四,89,88,87

王五,75,79,85


實現方式:

select name,’Chinese’ as subject,’Chinese’ as score from test3

union

select name,’math’ as subject,’math’ as score from test3

union 

select name,’English’ as subject,’math’ as score from test3;