498
技術社區[雲棲]
MaxCompute SQL-列轉行和行轉列
1. 假設我們在MaxCompute中有兩張表,其中一張表是存用戶基本信息,另一張表是存用戶的地址信息等,表數據假設如下:
user_basic_info:
id |
name |
1 |
a |
2 |
b |
3 |
c |
4 |
d |
user_address;
name |
address |
a |
add1 |
a |
add2 |
b |
add3 |
c |
add4 |
d |
add5 |
我們可以看到同一個用戶不止一個地址(這裏是假設的),我們需要把數據變為如下格式:
id |
name |
address |
1 |
a |
add1,add2 |
2 |
b |
add3 |
3 |
c |
add4 |
4 |
d |
add5 |
建表:
CREATE TABLE user_basic_info (
id string,
name string
);
CREATE TABLE user_address (
name string,
address string
);
插入數據:
insert into table user_basic_info
select '1','a' from (select count(1) from user_basic_info) t;
insert into table user_address
select 'a','add1' from (select count(1) from user_address) t;
執行合並:
select ubi.id, ubi.name, wm_concat(',', ua.address) as address from user_basic_info ubi join user_address ua on ubi.name=ua.name GROUP BY ubi.id, ubi.name;
運行結果:
運行結果:
1
a add1,add2
2
b add3
3
c add4
4 d add5
2. 假設我們有一張表:
user_info:
id |
name |
address |
1 |
a |
add1,add2 |
2 |
b |
add3 |
3 |
c |
add4 |
4 |
d |
add5 |
我們需要拆分address,變為:
id |
name |
address |
1 |
a |
add1 |
1 |
a |
add2 |
2 |
b |
add3 |
3 |
c |
add4 |
4 |
d |
add5 |
建表
CREATE TABLE user_info (
id string,
name string,
address string
);
插入數據(導入第一個實驗的結果)
insert into table user_info select ubi.id, ubi.name, wm_concat(',', ua.address) as address from user_basic_info ubi join user_address ua on ubi.name=ua.name GROUP BY ubi.id, ubi.name;
執行拆分:
select id, name, add_new from user_info ui lateral view explode(split(ui.address,',')) adtable as add_new;
結果為:
1 a
add1
1 a add2
2 b add3
3 c add4
4 d add5
最後更新:2017-06-27 17:31:56