首页 > 数据库 > 数据库开发技术 > SQL总结大厂真题-互相关注
1题目

2.考点
follower_ids是一个列表,所以需要进行展开,用到UDTF函数(列转行,炸裂函数)lateral view
字符串拼接函数concat_ws()
if()
3.SQL
step1:把follower_ids炸裂,转换成多行
-- 炸裂函数selectuser_id,follower_ids,follower_idfrom t_user_followerlateral view explode(split(follower_ids,',')) t as follower_id
执行结果

step2:把user和follower_id进行有序拼接,从而把0001关注0002和0002关注0001拼接成相同的字符串,使得两行有相同的内容,产生关联。
selectuser_id,follower_id,if(user_id<follower_id,concat_ws(',',user_id,follower_id),concat_ws(',',follower_id,user_id)) as friend,follower_idsfrom t_user_follower lateral view explode(split(follower_ids,',')) t as follower_id
执行结果

step3:根据拼接字符串进行统计,并限定行数为2,从而得到最终结果。
selectfriendfrom(selectuser_id,follower_ids,follower_id,if(user_id<follower_id,concat_ws(',',user_id,follower_id),concat_ws(',',follower_id,user_id)) as friendfrom t_user_follower lateral view explode(split(follower_ids,',')) t as follower_id)ttgroup by friendhaving count(1) =2
执行结果

4.建表语句
-- 建表语句create table t_user_follower(user_id string comment '用户id',follower_ids string comment '关注者列表');
-- 数据插入语句insert into t_user_follower values('0001','0002,0003'),('0002','0001,0003'),('0003','0004'),('0004','0001,0002');
原文作者:数据仓库技术;如有侵权,请联系管理员删除。