赞
踩
Hive 列转行
将某列转为数组返回,可以用collect_ws,collect_list函数,其中collect_ws去重,collect_list不去重。如需要返回字符串,可联合concat_ws函数指定分隔符。
1、对单列转行
列子:
原数据
id fruit
11 apple
11 peach
12 banana
12 banana
转化为(去重)
id fruit
11 apple,peach
12 banana
代码:
去重: select id,concat_ws(‘,’,collect_set(fruit)) from table_name group by id;
不去重:select id,concat_ws(‘,’collect_list(fruit)) from table_name group by id;
2、对多列转行
id name fruit amount
11 zhan apple 20
11 zhan peach 40
12 li banana 15
12 li banana 17
转化为(去重)
id name fruit amount
11 zhang apple,peach 20,40
12 li banana 15,17
代码:
去重: select id,name,concat_ws(‘,’,collect_set(fruit)),concat_ws(‘,’,collect_set(amount))
from table_name group by id,name;
不去重: select id,name,concat_ws(‘,’,collect_list(fruit)),concat_ws(‘,’,collect_list(amount))
from table_name group by id,name;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。