Skip to main content

LeetCode 534. Game Play Analysis III SQL Solution

Problem

LeetCode SQL Problem

  1. Game Play Analysis III

Activity table

player_iddevice_idevent_dategames_played
122016-03-015
122016-05-026
132017-06-251
312016-03-020
342018-07-035

Solution - Correlated Subquery

Game Play Analysis III
SELECT A.player_id
,A.event_date
,(
SELECT sum(B.games_played)
FROM Activity B
WHERE B.player_id = A.player_id
AND B.event_date <= A.event_date
) AS games_played_so_far
FROM Activity AS A
ORDER BY A.player_id
,A.event_date

Query Output

player_idevent_dategames_played_so_far
12016-03-015
12016-05-0211
12017-06-2512
32016-03-020
32018-07-035

Solution - Self Join

Game Play Analysis III
SELECT A.player_id
,A.event_date
,sum(B.games_played) AS games_played_so_far
FROM Activity AS A
INNER JOIN Activity AS B ON A.player_id = B.player_id
AND A.event_date >= B.event_date
GROUP BY A.player_id
,A.event_date
ORDER BY A.player_id
,A.event_date

Query Output

player_idevent_dategames_played_so_far
12016-03-015
12016-05-0211
12017-06-2512
32016-03-020
32018-07-035

Solution - Sum() Window Function

Game Play Analysis III
SELECT player_id
,event_date
,sum(games_played) OVER (
PARTITION BY player_id ORDER BY event_date
) AS games_played_so_far
FROM Activity

Query Output

player_idevent_dategames_played_so_far
12016-03-015
12016-05-0211
12017-06-2512
32016-03-020
32018-07-035