大数据第50天—Mysql练习题12道之五-活跃用户的总数-杨大伟
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了大数据第50天—Mysql练习题12道之五-活跃用户的总数-杨大伟,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2008字,纯文字阅读大概需要3分钟。
内容图文
有日志如下,请写出代码求得所有用户和活跃用户的总数及平均年龄。(活跃用户指连续两天都有访问记录的用户)
日期 用户 年龄
11,test_1,23
11,test_2,19
11,test_3,39
11,test_1,23
11,test_3,39
11,test_1,23
12,test_2,19
13,test_1,23
1 create table test_five_active( 2 active_time string COMMENT ‘活跃日期‘, 3user_id string COMMENT ‘用户id‘, 4 age int COMMENT ‘用户年龄‘5) 6 row format delimited fields terminated by‘\t‘;
1 insert into table test_five_active values (‘11‘,‘test_1‘,11); 2insertintotable test_five_active values (‘11‘,‘test_2‘,22); 3insertintotable test_five_active values (‘11‘,‘test_3‘,33); 4insertintotable test_five_active values (‘11‘,‘test_4‘,44); 5 6insertintotable test_five_active values (‘12‘,‘test_3‘,33); 7insertintotable test_five_active values (‘12‘,‘test_5‘,55); 8insertintotable test_five_active values (‘12‘,‘test_6‘,66); 910insertintotable test_five_active values (‘13‘,‘test_4‘,44); 11insertintotable test_five_active values (‘13‘,‘test_5‘,55); 12insertintotable test_five_active values (‘13‘,‘test_7‘,77);
1 -- 所有用户的总数及平均年龄 2 select 3 count(*) sum_user, 4avg(age) avg_age 5from 6( 7select 8user_id, 9avg(age) age 10from test_five_active 11groupbyuser_id12) t1; 1314-- 活跃人数的总数及平均年龄15select-- 最外一层算出活跃用户的个数以及平均年龄16count(*), 17avg(d.age) 18from19( 20select-- 最后还需要以user_id分组,去重(防止某个用户在11,12号连续活跃,然后在14,15号又连续活跃,导致diff求出不一致,所以此用户会出现两次)21 c.user_id, 22 c.age 23from24 ( 25select-- 以用户和差值diff分组,看分组下的数据的个数是否大于等于2(连续两天登录),取出活跃用户的数据26 b.user_id, 27 b.age, 28 b.diff, 29count(*) flag 30from31 ( 32select-- 用活跃日期减去排名,求出差值,看差值是否相等,相等差值的数据肯定是连续活跃的数据33 a.active_time, 34 a.user_id, 35 a.age, 36 a.rank_time, 37 a.active_time-a.rank_time diff 38from39 ( 40select-- 以用户和活跃日期分组(去重,防止某个用户在同一天活跃多次),求出每个用户的活跃日期排名41 active_time, 42user_id, 43 age, 44 rank() over(partition byuser_idorderby active_time) rank_time 4546from test_five_active 47groupby active_time,user_id,age 48 ) a 49 ) b 50groupby b.user_id,b.age,b.diff 51havingcount(*) >=252 ) c 53groupby c.user_id,c.age 54 ) d;
原文:https://www.cnblogs.com/shui68home/p/13591571.html
内容总结
以上是互联网集市为您收集整理的大数据第50天—Mysql练习题12道之五-活跃用户的总数-杨大伟全部内容,希望文章能够帮你解决大数据第50天—Mysql练习题12道之五-活跃用户的总数-杨大伟所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。