# Write your MySQL query statement below
512. 游戏玩法分析 II
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 | +-----------+-----------+
原站题解
mysql 解法, 执行用时: 437 ms, 内存消耗: 0 B, 提交时间: 2023-10-15 16:40:05
select player_id, device_id from activity where (player_id, event_date) in ( select player_id, min(event_date) from activity group by player_id )
pythondata 解法, 执行用时: 328 ms, 内存消耗: 61.3 MB, 提交时间: 2023-10-15 16:38:16
import pandas as pd def game_analysis(activity: pd.DataFrame) -> pd.DataFrame: data = activity.copy() # 窗口函数 data['rnk'] = data.groupby('player_id')['event_date'].rank(method='first') result = data[data['rnk'] == 1][['player_id', 'device_id']] # index筛选 # 使用 groupby 和 idxmin() 函数来找到每个 player_id 对应的最早的 event_date 的索引 earliest_indices = data.groupby('player_id')['event_date'].idxmin() # 通过索引选择相应的行,并提取 player_id 和 device_id 列 result = data.loc[earliest_indices, ['player_id', 'device_id']] return result
mysql 解法, 执行用时: 636 ms, 内存消耗: 0 B, 提交时间: 2023-10-15 16:37:56
select player_id, device_id from ( select player_id, device_id, dense_rank() over(partition by player_id order by event_date asc) rnk from activity ) a where rnk=1