Skip to main content

LeetCode 512. Game Play Analysis II SQL Solution

Problem

LeetCode SQL Problem

  1. Game Play Analysis II

Activity table

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

Solution - Group By + Subquery

Report the device that is first logged in for each player
-- Use a subquery to report the first login date for each player.
-- For first login records, find out the device_id of each player_id
SELECT
player_id,
device_id
FROM
Activity
WHERE
(player_id, event_date) IN (
SELECT
player_id,
min(event_date) AS first_login
FROM
Activity
GROUP BY
player_id
)

Query Output

player_iddevice_id
12
23
31

Solution - First_Value() Window Function

Report the device that is first logged in for each player
-- Use First_Value() Window Function to figure out the first device_id for each player_id
-- Use DISTINCT keyword to return unique player_id and device_id combination
WITH PlayerFirstDevice
AS (
SELECT *
,first_value(device_id) OVER (
PARTITION BY player_id ORDER BY event_date ASC
) AS first_device_id
FROM Activity
)
SELECT DISTINCT player_id
,first_device_id AS device_id
FROM PlayerFirstDevice

Query Output

player_iddevice_id
12
23
31