Leetcode 534 Game Play Analysis III without sum window function

Kenneth Law
2 min readJan 20, 2022
Input: 
Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 1 | 3 | 2017-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2018-07-03 | 5 |
+-----------+-----------+------------+--------------+
Output:
+-----------+------------+---------------------+
| player_id | event_date | games_played_so_far |
+-----------+------------+---------------------+
| 1 | 2016-03-01 | 5 |
| 1 | 2016-05-02 | 11 |
| 1 | 2017-06-25 | 12 |
| 3 | 2016-03-02 | 0 |
| 3 | 2018-07-03 | 5 |
+-----------+------------+---------------------+
Explanation:
For the player with id 1, 5 + 6 = 11 games played by 2016-05-02, and 5 + 6 + 1 = 12 games played by 2017-06-25.
For the player with id 3, 0 + 5 = 5 games played by 2018-07-03.
Note that for each player we only care about the days when the player logged in.

This question have two solutions 1) SUM() window function 2) self-join/two table.

The condition in the solution. Meaning of “a.event_date>=b.event_date” is to calculate a running total.

select a1.player_id, a1.event_date, sum(a2.games_played) as games_played_so_far
from Activity a1, Activity a2
where a1.player_id = a2.player_id and a1.event_date >= a2.event_date
group by a1.player_id, a1.event_date
order by a1.player_id, a1.event_date

Finally to use a ‘Group by date’ to calculate running total.

--

--