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 |
+-----------+-----------+
这题看上去与 LeetCode–511. 游戏玩法分析 I 相似, 但用到的思想有一定的差异, 一开始想借用这题的思路找到结果
select a.player_id, a.device_id from (select player_id, device_id, min(event_date) as first_login from Activity group by player_id) a
测试用用例
| player_id | device_id | event_date | games_played |
| --------- | --------- | ---------- | ------------ |
| 1 | 2 | 2016-03-01 | 5 |
| 1 | 2 | 2016-05-02 | 6 |
| 1 | 3 | 2015-06-25 | 1 |
| 3 | 1 | 2016-03-02 | 0 |
| 3 | 4 | 2016-02-03 | 5 |
预期结果
| player_id | device_id |
| --------- | --------- |
| 1 | 3 |
| 3 | 4 |
实际输出
| player_id | device_id |
| --------- | --------- |
| 1 | 2 |
| 3 | 1 |
解题思路
rank() + over()
组合函数实现, 按照 player_id
分组, 查询最早登录的 event_date
和 device_id
rank = 1
的数据select a.player_id, a.device_id from
(select player_id, device_id, rank() over(partition by player_id order by event_date) as 'rank' from Activity) a
where a.rank = 1