Skip to content

Commit 84ec9b4

Browse files
authored
Add files via upload
1 parent 4b1aa50 commit 84ec9b4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Medium/Game Play Analysis 4.sql

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
-- Question 91
2+
-- Table: Activity
3+
4+
-- +--------------+---------+
5+
-- | Column Name | Type |
6+
-- +--------------+---------+
7+
-- | player_id | int |
8+
-- | device_id | int |
9+
-- | event_date | date |
10+
-- | games_played | int |
11+
-- +--------------+---------+
12+
-- (player_id, event_date) is the primary key of this table.
13+
-- This table shows the activity of players of some game.
14+
-- Each row is a record of a player who logged in and played a number of games (possibly 0)
15+
-- before logging out on some day using some device.
16+
17+
18+
-- Write an SQL query that reports the fraction of players that logged in again
19+
-- on the day after the day they first logged in, rounded to 2 decimal places.
20+
-- In other words, you need to count the number of players that logged in for at least two consecutive
21+
-- days starting from their first login date, then divide that number by the total number of players.
22+
23+
-- The query result format is in the following example:
24+
25+
-- Activity table:
26+
-- +-----------+-----------+------------+--------------+
27+
-- | player_id | device_id | event_date | games_played |
28+
-- +-----------+-----------+------------+--------------+
29+
-- | 1 | 2 | 2016-03-01 | 5 |
30+
-- | 1 | 2 | 2016-03-02 | 6 |
31+
-- | 2 | 3 | 2017-06-25 | 1 |
32+
-- | 3 | 1 | 2016-03-02 | 0 |
33+
-- | 3 | 4 | 2018-07-03 | 5 |
34+
-- +-----------+-----------+------------+--------------+
35+
36+
-- Result table:
37+
-- +-----------+
38+
-- | fraction |
39+
-- +-----------+
40+
-- | 0.33 |
41+
-- +-----------+
42+
-- 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
43+
44+
-- Solution
45+
With t as
46+
(select player_id,
47+
min(event_date) over(partition by player_id) as min_event_date,
48+
case when event_date- min(event_date) over(partition by player_id) = 1 then 1
49+
else 0
50+
end as s
51+
from Activity)
52+
53+
select round(sum(t.s)/count(distinct t.player_id),2) as fraction
54+
from t

0 commit comments

Comments
 (0)