Formatted question description: https://leetcode.ca/all/550.html
550. Game Play Analysis IV
Level
Medium
Description
Table: Activity
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| player_id | int |
| device_id | int |
| event_date | date |
| games_played | int |
+--------------+---------+
(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.
Write an SQL query that reports the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
The query result format is in the following example:
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 |
+-----------+
Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33
Solution
To obtain a fraction, both the numerator and the denominator needs to be obtained.
To obtain the numerator, for each player_id
, check whether the player logged back in on the day just after the first day that the player logged in, and count the number of player_id
s that meet such requirement.
The denominator is simply the number of distinct player_id
s.
The result is the numerator divided by the denominator.
Join the Activity
table with itself, and for each player_id
, obtain the sum of games_played
from the entries that are earlier than or equal to each event_date
.
# Write your MySQL query statement below
select round(
ifnull(
(
select count(distinct a.player_id)
from Activity as a join Activity as b
on a.player_id = b.player_id and datediff(b.event_date, a.event_date) = 1
where a.event_date = (
select min(event_date) from Activity where player_id = a.player_id
)
)
/ -- devided by
( select count(distinct player_id) from Activity ),
0),
2)
as fraction;