leetcode1079:游戏玩法分析——求留存率

求留存率

题目描述

表:Activity

±-------------±--------+

| Column Name | Type |

±-------------±--------+

| player_id | int |

| device_id | int |

| event_date | date |

| games_played | int |

±-------------±--------+

(player_id,event_date)是此表的主键(具有唯一值的列的组合)

这张表显示了某些游戏的玩家的活动情况

每一行表示一个玩家的记录,在某一天使用某个设备注销之前,登录并玩了很多游戏(可能是 0)

玩家的 安装日期 定义为该玩家的第一个登录日。

我们将日期 x 的 第一天留存率 定义为:假定安装日期为 X 的玩家的数量为 N ,其中在 X 之后的一天重新登录的玩家数量为 M,M/N 就是第一天留存率,四舍五入到小数点后两位。

编写解决方案,报告所有安装日期、当天安装游戏的玩家数量和玩家的 第一天留存率。

以 任意顺序 返回结果表。

结果格式如下所示。

题解

t1:查询所有玩家首次安装游戏的时间

sql 复制代码
select
player_id,
min(event_date) as install_dt
from Activity
group by player_id

t2:查询当天安装该游戏的玩家数量

sql 复制代码
select t1.install_dt,
count(player_id) as installs
from 
    (select
    player_id,
    min(event_date) as install_dt
    from Activity
    group by player_id) t1

t3:查询安装第二天仍然登录游戏的玩家

sql 复制代码
select 
t1.install_dt,
count(a.player_id) as Day1_nums
from Activity a
left join 
    (select
    player_id,
    min(event_date) as install_dt
    from Activity
    group by player_id) t1
on a.event_date = date_add(t1.install_dt,interval 1 day)
and a.player_id = t1.player_id
where install_dt is not null
group by install_dt

将以上进行综合,并用t3中的第二天仍登录数量/首次登录的玩家数量,等于留存率。

即最终代码如下:

sql 复制代码
select t1.install_dt,
count(player_id) as installs,
ifnull(round(Day1_nums/count(player_id),2),0) as Day1_retention
from 
    (select
    player_id,
    min(event_date) as install_dt
    from Activity
    group by player_id) t1
left join
(
select 
t1.install_dt,
count(a.player_id) as Day1_nums
from Activity a
left join 
    (select
    player_id,
    min(event_date) as install_dt
    from Activity
    group by player_id) t1
on a.event_date = date_add(t1.install_dt,interval 1 day)
and a.player_id = t1.player_id
where install_dt is not null
group by install_dt) t3
on t1.install_dt = t3.install_dt
group by t1.install_dt

题目来源:力扣

相关推荐
夜天炫安全3 小时前
数据结构中所需的C语言基础
c语言·数据结构·算法
小陳参上4 小时前
用Python创建一个Discord聊天机器人
jvm·数据库·python
2301_789015624 小时前
DS进阶:AVL树
开发语言·数据结构·c++·算法
changhong19865 小时前
如何在 Spring Boot 中配置数据库?
数据库·spring boot·后端
qyzm7 小时前
天梯赛练习(3月13日)
开发语言·数据结构·python·算法·贪心算法
执笔画情ora7 小时前
Postgresql数据库管理-pg_xact
数据库·postgresql·oracle
逆境不可逃7 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
南棱笑笑生7 小时前
20260310在瑞芯微原厂RK3576的Android14查看系统休眠时间
服务器·网络·数据库·rockchip
CoderCodingNo8 小时前
【GESP】C++五级练习题 luogu-P1182 数列分段 Section II
开发语言·c++·算法
放下华子我只抽RuiKe58 小时前
机器学习全景指南-直觉篇——基于距离的 K-近邻 (KNN) 算法
人工智能·gpt·算法·机器学习·语言模型·chatgpt·ai编程