SQL查询语句怎样算用户的登录天数的
Admin 2022-08-05 群英技术资讯 976 次浏览
在这篇文章中,我们来学习一下“SQL查询语句怎样算用户的登录天数的”的相关知识,下文有详细的讲解,易于大家学习和理解,有需要的朋友可以借鉴参考,下面就请大家跟着小编的思路一起来学习一下吧。求解用户登陆信息表中,每个用户连续登陆平台的天数,连续登陆基础为汇总日期必须登陆,表中每天只有一条用户登陆数据(计算中不涉及天内去重)。
表描述:user_id:用户的id;
sigin_date:用户的登陆日期。
注:求解过程有多种方式,下述求解解法为笔者思路,其他解法可在评论区交流。
思路:
该问题的突破的在于登陆时间,计算得到连续登陆标识,以标识分组为过滤条件,得到连续登陆的天数,最后以user_id分组,以count()函数求和得到每个用户的连续登陆天数。
连续登陆标识 =(当日登陆日期 - 用户的登陆日期)- 开窗排序的顺序号(倒序)
-- 1.建表语句
drop table if exists test_sigindate_cnt;
create table test_sigindate_cnt(
user_id string
,sigin_date string
)
;
-- 2.测试数据插入语句
insert overwrite table test_sigindate_cnt
select 'uid_1' as user_id,'2021-08-03' as sigin_date
union all
select 'uid_1' as user_id,'2021-08-04' as sigin_date
union all
select 'uid_1' as user_id,'2021-08-01' as sigin_date
union all
select 'uid_1' as user_id,'2021-08-02' as sigin_date
union all
select 'uid_1' as user_id,'2021-08-05' as sigin_date
union all
select 'uid_1' as user_id,'2021-08-06' as sigin_date
union all
select 'uid_2' as user_id,'2021-08-01' as sigin_date
union all
select 'uid_2' as user_id,'2021-08-05' as sigin_date
union all
select 'uid_2' as user_id,'2021-08-02' as sigin_date
union all
select 'uid_2' as user_id,'2021-08-06' as sigin_date
union all
select 'uid_3' as user_id,'2021-08-04' as sigin_date
union all
select 'uid_3' as user_id,'2021-08-06' as sigin_date
union all
select 'uid_4' as user_id,'2021-08-03' as sigin_date
union all
select 'uid_4' as user_id,'2021-08-02' as sigin_date
;
select user_id
,count(1) as sigin_cnt
from (
select
user_id
,datediff('2021-08-06',sigin_date) as data_diff
,row_number() over (partition by user_id order by sigin_date desc) as row_num
from test_sigindate_cnt
) t
where data_diff - row_num = -1
group by
user_id
;
| 汇总日期 | 用户id | 登陆天数 |
| 2021-08-06 | uid_1 | 6 |
| 2021-08-06 | uid_2 | 2 |
| 2021-08-06 | uid_3 | 1 |

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要为大家介绍了SQL Server 数据库基础编程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
SQL LIKE 运算符,在WHERE子句中使用LIKE运算符来搜索列中的指定模式。有不少朋友对于SQL LIKE运算符比较感兴趣,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。
这篇文章主要介绍了sql通过日期判断年龄函数,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
这篇文章主要介绍了SQLSERVER 拼接含有变量字符串案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
这篇文章主要介绍了SQL Server数据表字段自定义自增数据格式的方法,结合实例形式分析了SQL Server自增数据格式的定义方法与具体实现步骤,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008