gpt4 book ai didi

hadoop - 如何在配置单元中转置/旋转数据?

转载 作者:可可西里 更新时间:2023-11-01 14:09:08 26 4
gpt4 key购买 nike

我知道没有直接的方法可以在配置单元中转置数据。我关注了这个问题:Is there a way to transpose data in Hive? , 但由于那里没有最终答案,无法一路走下去。

这是我的表格:

 | ID   |   Code   |  Proc1   |   Proc2 | 
| 1 | A | p | e |
| 2 | B | q | f |
| 3 | B | p | f |
| 3 | B | q | h |
| 3 | B | r | j |
| 3 | C | t | k |

这里 Proc1 可以有任意数量的值。 ID、Code 和 Proc1 共同构成了该表的唯一键。我想旋转/转置此表,以便 Proc1 中的每个唯一值成为一个新列,而 Proc2 中的相应值是相应行在该列中的值。本质上,我试图得到类似的东西:

 | ID   |   Code   |  p   |   q |  r  |   t |
| 1 | A | e | | | |
| 2 | B | | f | | |
| 3 | B | f | h | j | |
| 3 | C | | | | k |

在新转换的表中,ID和code是唯一的主键。从我上面提到的票证,我可以使用 to_map UDAF 走到这一步。 (免责声明 - 这可能不是朝着正确方向迈出的一步,但如果是的话,请在此提及)

 | ID   |   Code   |  Map_Aggregation   | 
| 1 | A | {p:e} |
| 2 | B | {q:f} |
| 3 | B | {p:f, q:h, r:j } |
| 3 | C | {t:k} |

但不知道如何从这一步到我想要的数据透视表/转置表。任何关于如何进行的帮助都会很棒!谢谢。

最佳答案

这是我使用 hive 的内部 UDF 函数“map”解决这个问题的方法:

select
b.id,
b.code,
concat_ws('',b.p) as p,
concat_ws('',b.q) as q,
concat_ws('',b.r) as r,
concat_ws('',b.t) as t
from
(
select id, code,
collect_list(a.group_map['p']) as p,
collect_list(a.group_map['q']) as q,
collect_list(a.group_map['r']) as r,
collect_list(a.group_map['t']) as t
from (
select
id,
code,
map(proc1,proc2) as group_map
from
test_sample
) a
group by
a.id,
a.code
) b;

“concat_ws”和“map”是 hive udf,“collect_list”是 hive udaf。

关于hadoop - 如何在配置单元中转置/旋转数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com