Hive行轉列,列轉行

2021-08-07 12:28:51 字數 2629 閱讀 8484

下面舉兩個例子:

例一:行轉列

資料: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) 函式返回字串連線後的結果,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 如果a

為true返回b

如果a為false返回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;

Hive 行轉列 列轉行

並不是真正意義上的行轉列 列轉行。只是這樣叫的。concat stringa,stringb,stringc 返回輸入字串拼接後的結果,支援輸入任意多個字串 測試結果 可以連線任意多個 concat ws 分隔符 stringa,stringb 是乙個特殊的concat 第乙個引數是引數間的分隔符 ...

hive 列轉行 HQL 行轉列,列轉行

1 相關函式 concat string a col,string b col 返回輸入字串連線後的結果,支援任意個輸入字串 concat ws separator,str1,str2,它是乙個特殊形式的 concat 第乙個引數剩餘引數間的分隔符。分隔符可以是與剩餘引數一樣的字串。如果分隔符是 n...

hive 列轉行和行轉列

1.假設我們在hive中有兩張表,其中一張表是存使用者基本資訊,另一張表是存使用者的位址資訊等,表資料假設如下 user basic info id name1a 2b3c 4duser address name address aadd1 aadd2 badd3 cadd4 dadd5 id na...