行转列的常规做法是,group by+sum(if())【或count(if())】
例题:
腾讯QQ
假设tableA如表5, tableB如表6,
表5
qq号(字段名:qq) | 游戏(字段名:game) |
---|---|
10000 | a |
10000 | b |
10000 | c |
20000 | c |
20000 | d |
表6
qq号(字段名:qq) | 游戏(字段名:game) |
---|---|
10000 | a_b_c |
20000 | c_d |
请写出以下sql逻辑:
a, 将tableA输出为tableB的格式; 【行转列】
b, 将tableB输出为tableA的格式; 【列转行】
create table tableA(qq string, game string)
insert overwrite table tableA values (10000, 'a'),(10000, 'b'),(10000, 'c'),(20000, 'c'),(20000, 'd');create table tableB(qq string, game string) ;
insert overwrite table tableB values
(10000, 'a_b_c'),
(20000, 'c_d');
将tableA输出为tableB的格式
select qq,concat_ws('_', collect_list(game)) game
from tableA
group by qq;
将tableB输出为tableA的格式
select qq,tmp.game
from tableB lateral view explode(split(game, '_')) tmp as game;