当前位置:网站首页>如何分析粉丝兴趣?
如何分析粉丝兴趣?
2022-07-06 19:27:00 【猴子数据分析】
【题目】
有一张“粉丝关注表”,包含3个字段:用户id、关注媒体id、日期。
【问题】“粉丝关注表”中存在一个用户同时关注多个媒体的情况存在,比如:用户id为A001的用户,对应关注媒体id数据为1010,1020,1031。为了便于后期分析粉丝兴趣,请将该表中的这种情况进行拆分为多条。
比如对于用户A001,其转换如下:
【解题思路】
这类问题称为“列转行”,在MySQL里的处理方式一般分为三步:
1)创建一个“序列表”;
2)进行多表联结,将原表的每一条数据复制为多条;
3)使用substring_index函数获取最终结果。
第一步:创建序列表
“序列表”是指只有一个字段,存储的是数字序列,比如:
其中,“序列”的最大值就是该问题中一个用户关注媒体的最多个数。
select max(length(关注媒体id) - length(replace(关注媒体id,',','')) + 1) as 最多关注媒体个数
from 粉丝关注表;
返回结果为:
那我们需要新建的“序列表”就是:
第二步:多表联结
使用多表联结,可以通过“序列表”将“粉丝关注表”的每行变成多行。
此处有两个注意点:
1)为保证原表中的每一条数据不丢失,选择“左联结”,并以原表为左表;
2)联结条件里对复制条数进行限制,限制条件是用户关注媒体的数量,即“关注媒体id”字段下的逗号数量加1。
select t1.用户id,
t1.关注媒体id,
t1.日期,
t2.序列
from 粉丝关注表 t1
left join 序列表 t2 on t2.序列 <= (length(关注媒体id) - length(replace(关注媒体id,',','')) + 1);
返回结果为:
第三步:使用函数获取结果
接下来就是将媒体id截取出来,需要用到字符串截取函数:SUBSTRING_INDEX。
SUBSTRING_INDEX(字符串,分隔符,参数)
其中,分隔符指本题中分割媒体id的“,”;2指按分隔符分开,从左往右截取几个媒体id;如果参数为负数时,表示从右往左截取几个媒体id。
select t1.用户id,
substring_index(substring_index(t1.关注媒体id,',',t2.序列),',',-1) as 关注媒体id,
t1.日期
from 粉丝关注表 t1
left join 序列表 t2 on t2.序列 <= (length(关注媒体id) - length(replace(关注媒体id,',','')) + 1);
返回结果为:
【本题考点】
1)考查对序列表的了解;
2)考查对字符串截取函数SUBSTRING_INDEX的了解;
3)考查对多表联结的了解。
▼ 点击「阅读原文」
▼ 解锁更多数据分析课程
边栏推荐
猜你喜欢
如何设计好接口测试用例?教你几个小技巧,轻松稿定
NuScenes数据集关于Radar数据的统计
MATLB|具有储能的经济调度及机会约束和鲁棒优化
Redis入门完整教程:复制配置
Babbitt | metauniverse daily must read: is IP authorization the way to break the circle of NFT? What are the difficulties? How should holder choose the cooperation platform
[secretly kill little partner pytorch20 days] - [Day1] - [example of structured data modeling process]
Use of promise in ES6
Redis introduction complete tutorial: replication principle
导数、偏导数、方向导数
MySQL - common functions - string functions
随机推荐
Apifox, is your API interface document rolled up like this?
MES管理系统的应用和好处有哪些
CSDN 夏令营课程 项目分析
Redis introduction complete tutorial: replication principle
巴比特 | 元宇宙每日必读:IP授权是NFT的破圈之路吗?它的难点在哪里?Holder该如何选择合作平台?...
QPushButton-》函数精解
你不可不知道的Selenium 8种元素定位方法,简单且实用
Redis入门完整教程:RDB持久化
【软件测试】最全面试问题和回答,全文背熟不拿下offer算我输
Data analysis from the perspective of control theory
Static proxy of proxy mode
写作系列之contribution
S120驱动器基本调试步骤总结
从零安装Redis
Detailed explanation of 19 dimensional integrated navigation module sinsgps in psins (time synchronization part)
CDB PDB user rights management
MySQL is an optimization artifact to improve the efficiency of massive data query
CDB PDB 用户权限管理
[software test] the most complete interview questions and answers. I'm familiar with the full text. If I don't win the offer, I'll lose
Difference and the difference between array and array structure and linked list