comments | difficulty | edit_url | tags | |
---|---|---|---|---|
true |
简单 |
|
Table: Activity
+--------------+---------+ | Column Name | Type | +--------------+---------+ | player_id | int | | device_id | int | | event_date | date | | games_played | int | +--------------+---------+ (player_id, event_date) 是这个表的两个主键(具有唯一值的列的组合) 这个表显示的是某些游戏玩家的游戏活动情况 每一行是在某天使用某个设备登出之前登录并玩多个游戏(可能为0)的玩家的记录
请编写解决方案,描述每一个玩家首次登陆的设备名称
返回结果格式如以下示例:
示例 1:
输入: Activity table: +-----------+-----------+------------+--------------+ | player_id | device_id | event_date | games_played | +-----------+-----------+------------+--------------+ | 1 | 2 | 2016-03-01 | 5 | | 1 | 2 | 2016-05-02 | 6 | | 2 | 3 | 2017-06-25 | 1 | | 3 | 1 | 2016-03-02 | 0 | | 3 | 4 | 2018-07-03 | 5 | +-----------+-----------+------------+--------------+ 输出: +-----------+-----------+ | player_id | device_id | +-----------+-----------+ | 1 | 2 | | 2 | 3 | | 3 | 1 | +-----------+-----------+
我们可以使用 GROUP BY
和 MIN
函数来找到每个玩家的第一次登录日期,然后使用联合键子查询来找到每个玩家的第一次登录设备。
# Write your MySQL query statement below
SELECT
player_id,
device_id
FROM Activity
WHERE
(player_id, event_date) IN (
SELECT
player_id,
MIN(event_date) AS event_date
FROM Activity
GROUP BY 1
);
我们可以使用窗口函数 rank()
,它可以为每个玩家的每个登录日期分配一个排名,然后我们可以选择排名为
# Write your MySQL query statement below
WITH
T AS (
SELECT
*,
RANK() OVER (
PARTITION BY player_id
ORDER BY event_date
) AS rk
FROM Activity
)
SELECT player_id, device_id
FROM T
WHERE rk = 1;