源表结构:
pcgid string
mobilegid string
value double
测试数据如下:
p1 m1 0.6
p1 m2 0.9
p2 m1 1.0
需要的结果是:
p1 {"m2":"0.9","m1":"0.6"} 2
p2 {"m1":"1.0"} 1
就是对源表进行group by之后对另外两个字段变成key-value存成一个map
把mobilegid和value先连接成字符串,然后再把整个set的结果连接成一个字符串,最后再用str_to_map,完美解决
select pcgid as gid,
str_to_map(concat_ws(",",collect_set(concat_ws(':', mobilegid, cast(value as string)))))
as gids,
count(1) as num
from gemini_product_id_connect_result_pair
group by pcgid;
原文链接:http://www.cnblogs.com/qwj-sysu/p/5521194.html
清洗了一些埋点的数据,要求是将一张表中特定字段的行进行合并,并且不对重复的数据进行去重如下,数据形式如下,要对from字段进行进行合并:
一开始用collect_set函数实现,发现对字段进行去重了,后来发现collect_list函数可以实现,现将两者的区别总结如下:
1、concat_ws和collect_set()函数实现(对某列进行去重)
其作用是将多行某些列的多行进行去重合并,并通过&符号进行连接,代码如下
select subtype,
concat_ws('&',collect_set(cast(from as string))) from,
concat_ws('&',collect_set(cast(id as string))) id,
concat_ws('&',collect_set(cast(name as string)))name,
concat_ws('&',collect_set(cast(type as string))) type
from aaaaaaa
group by subtype;
效果如下:
2、concat_ws和collect_list()函数实现(对某列不进行去重)
select subtype,
concat_ws('&',collect_list(cast(from as string))) from,
concat_ws('&',collect_list(cast(id as string))) id,
concat_ws('&',collect_list(cast(name as string)))name,
concat_ws('&',collect_list(cast(type as string))) type
from aaaaaaa
group by subtype;
效果如下:
---------------------
作者:数据小白的进阶之路
原文:https://blog.csdn.net/weixin_37536446/article/details/80597480