LeetCode刷题-数据库(MySQL)- 512.Game Play Analysis II

512.Game Play Analysis II

一、题目描述

Table: Activity

Column Name Type
player_id int
device_id int
event_date date
games_played int

(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some game.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on some day using some device.

Write a SQL query that reports the device that is first logged in for each player.
The query result format is in the following example:
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

Result table:

player_id device_id
1 2
2 3
3 1

二、思路分析

先找出每个player_id对应的最早登录日期,将其作为一个临时表右连接原表,并通过ON筛选出符合题意的结果。

三、代码实现

SELECT
	a.player_id, a.device_id
FROM
	Activity a
RIGHT JOIN (
		SELECT 
			player_id,
			min(event_date) AS first_date
		FROM
			Activity
		GROUP BY player_id	
	) b
ON
	a.event_date = b.first_date
WHERE
	a.player_id = b.player_id;

你可能感兴趣的:(MySQL)