ITPub博客

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

SQL总结大厂真题-互相关注

原创 数据库开发技术 作者:晨曦_001 时间:2023-03-08 08:01:00 0 删除 编辑

1题目

现有用户关注者列表记录表t_user_follower,有两个字段,用户ID(user_id),关注者列表(follower_ids),关注者列表中是关注用户的用户ID,数据样例如下:
请找出互相关注的用户

2.考点

  1. follower_ids是一个列表,所以需要进行展开,用到UDTF函数(列转行,炸裂函数)lateral view

  2. 字符串拼接函数concat_ws()


  3. if()

3.SQL

step1:把follower_ids炸裂,转换成多行

-- 炸裂函数select  user_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拼接成相同的字符串,使得两行有相同的内容,产生关联。

select    user_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,从而得到最终结果。

select    friendfrom    (        select            user_id,            follower_ids,            follower_id,            if(user_id<follower_id,concat_ws(',',user_id,follower_id),concat_ws(',',follower_id,user_id)) as friend        from 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');


原文作者:数据仓库技术;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论
公众号:数据仓库技术 数据仓库技术:https://dwsql.com spark内置函数手册: https://sparkfunctions.com

注册时间:2022-12-18

  • 博文量
    116
  • 访问量
    55261