leetcode550. 游戏玩法分析 IV(SQL)

Table: Activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+
(player_id,event_date)是此表的主键。
这张表显示了某些游戏的玩家的活动情况。
每一行是一个玩家的记录,他在某一天使用某个设备注销之前登录并玩了很多游戏(可能是 0)。
 

编写一个 SQL 查询,报告在首次登录的第二天再次登录的玩家的分数,四舍五入到小数点后两位。换句话说,您需要计算从首次登录日期开始至少连续两天登录的玩家的数量,然后除以玩家总数。

查询结果格式如下所示:

Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-03-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+

Result table:
+-----------+
| fraction  |
+-----------+
| 0.33      |
+-----------+
只有 ID 为 1 的玩家在第一天登录后才重新登录,所以答案是 1/3 = 0.33

思路:分析:总玩家好求,下面看怎么求第一第二天都登陆的用户数。

做自连接:条件是,1、左表的日期等于嵌套查询出的最小日期 2、左表右表的玩家id相同 3、右表日期是左表的下一天

求出结果用round取两位即可。

select round(
            (select count(distinct b.player_id)
            from Activity as b,Activity as c
            where b.event_date=(select min(temp.event_date) from Activity as temp where temp.player_id=b.player_id) and 
            b.player_id=c.player_id and
            DATEDIFF(b.event_date,c.event_date)=-1)/count(distinct a.player_id)
        ,2) as 'fraction'
from Activity as a;
发布了552 篇原创文章 · 获赞 1万+ · 访问量 132万+

猜你喜欢

转载自blog.csdn.net/hebtu666/article/details/104322396