1. 假设我们在hive中有两张表,其中一张表是存用户基本信息,另一张表是存用户的地址信息等,表数据假设如下:
user_basic_info:
| id | name |
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 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 |
两个函数解释如下见:http://www.cnblogs.com/end/archive/2012/06/18/2553682.html
建表:
create table user_basic_info(id string, name string);
create table user_address(name string, address string);
加载数据:
load data local inpath '/home/jthink/work/workspace/hive/row_col_tran/data1' into table user_basic_info;
load data local inpath '/home/jthink/work/workspace/hive/row_col_tran/data2' into table user_address;
执行合并:
select max(ubi.id), ubi.name, concat_ws(',', collect_set(ua.address)) as address from user_basic_info ubi join user_address ua on ubi.name=ua.name group by 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 |
| id | name | address |
| 1 | a | add1 |
| 1 | a | add2 |
| 2 | b | add3 |
| 3 | c | add4 |
| 4 | d | add5 |
我们很容易想到用UDTF,explode():
select explode(address) as address from user_info;
这样执行的结果只有address, 但是我们需要完整的信息:
select id, name, explode(address) as address from user_info;
这样做是不对的, UDTF's are not supported outside the SELECT clause, nor nested in expressions
所以我们需要这样做:
select id, name, add from user_info ui lateral view explode(ui.address) adtable as add;
结果为:
1 a add1
1 a add2
2 b add3
3 c add4
4 d add5

本文详细介绍了如何使用Hive进行数据的行转列操作,包括合并不同表中的数据和拆分数据列,通过使用内置UDF如collect_set和concat_ws实现数据格式的灵活转换。同时,展示了如何利用UDTF explode()对数据进行拆分处理,以及在外部选择语句中正确使用explode()的方法。
7727

被折叠的 条评论
为什么被折叠?



