Hive--sql中的explode()函數和posexplode()函數

實現多列轉多行

  1. 先創建一個txt文件(最好是用notepad++,注意將編碼設置爲utf-8)如下:
    在這裏插入圖片描述
  2. 將該文件放到hive下的一個目錄中(可以自己指定目錄),我是將它放在一個data目錄中
    在這裏插入圖片描述
  3. 在hive的一個數據庫中創建一個表來進行操作,指定表名test.a,加入兩個字段id和tim,並在一行中用空格分隔,每行之間用\n進行分隔。
create table if not exists test.a(
     id STRING,
     tim STRING
)
row format delimited fields terminated by '-' 
lines terminated by '\n';
  1. 將開始創建的文件中的數據加載進新建的表中
load data local inpath 'opt/data/shijian.txt' into table test.a;
  1. 現在可以看看我們新創建的這個表中的數據
hive> load data local inpath 'opt/data/shijian.txt' into table test.a;
Loading data to table test.a
Table test.a stats: [numFiles=1, numRows=0, totalSize=56, rawDataSize=0]
OK
Time taken: 0.654 seconds
hive> select * from test.a;                                           
OK
a.id	a.tim
a,b,c,d	2:00,3:00,4:00,5:00
f,b,c,d	1:10,2:20,3:30,4:40
Time taken: 0.125 seconds, Fetched: 2 row(s)
  1. 現在先進行一列轉多行的操作,這裏就用到了explode()函數,將第二列tim中的數據用逗號切分併成爲第三列,操作如下
select id,tim,single_tim 
from test.a lateral view explode(split(tim,',')) t as single_tim
id	tim	single_tim
a,b,c,d	2:00,3:00,4:00,5:00	2:00
a,b,c,d	2:00,3:00,4:00,5:00	3:00
a,b,c,d	2:00,3:00,4:00,5:00	4:00
a,b,c,d	2:00,3:00,4:00,5:00	5:00
f,b,c,d	1:10,2:20,3:30,4:40	1:10
f,b,c,d	1:10,2:20,3:30,4:40	2:20
f,b,c,d	1:10,2:20,3:30,4:40	3:30
f,b,c,d	1:10,2:20,3:30,4:40	4:40
Time taken: 51.289 seconds, Fetched: 8 row(s)

可以看出上面的代碼實現了對第二列的多行轉換,現在如果想實現對兩列聽同事進行多行轉換,那麼用explode()函數就不能實現了,但可以用posexplode()函數,因爲該函數可以將index和數據都取出來,使用兩次posexplode並令兩次取到的index相等就行了。

  1. 使用一次posexplode()函數效果如下:
select id,tim,single_id_index,single_id from test.a 
lateral view posexplode(split(id,',')) t as single_id_index, single_id;d;
id	tim	single_id_index	single_id
a,b,c,d	2:00,3:00,4:00,5:00	0	a
a,b,c,d	2:00,3:00,4:00,5:00	1	b
a,b,c,d	2:00,3:00,4:00,5:00	2	c
a,b,c,d	2:00,3:00,4:00,5:00	3	d
f,b,c,d	1:10,2:20,3:30,4:40	0	f
f,b,c,d	1:10,2:20,3:30,4:40	1	b
f,b,c,d	1:10,2:20,3:30,4:40	2	c
f,b,c,d	1:10,2:20,3:30,4:40	3	d
Time taken: 43.6 seconds, Fetched: 8 row(s)
  1. 使用兩次posexplode()函數實現多列轉多行
select id,tim,single_id,single_tim from test.a 
lateral view posexplode(split(id,',')) t as single_id_index, single_id
lateral view posexplode(split(tim,',')) t as single_yim_index, single_tim
where single_id_index = single_yim_index;
id	tim	single_id	single_tim
a,b,c,d	2:00,3:00,4:00,5:00	a	2:00
a,b,c,d	2:00,3:00,4:00,5:00	b	3:00
a,b,c,d	2:00,3:00,4:00,5:00	c	4:00
a,b,c,d	2:00,3:00,4:00,5:00	d	5:00
f,b,c,d	1:10,2:20,3:30,4:40	f	1:10
f,b,c,d	1:10,2:20,3:30,4:40	b	2:20
f,b,c,d	1:10,2:20,3:30,4:40	c	3:30
f,b,c,d	1:10,2:20,3:30,4:40	d	4:40

這樣就可以實現了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章