I have the following tables:
Player_Attributes
| player_api_id | overall_rating | date |
|---|---|---|
| 30717 | 93 | '2007' |
| 30829 | 93 | '2007' |
| 30893 | 91 | '2008' |
| 30657 | 91 | '2008' |
Player
| player_api_id | player_name |
|---|---|
| 30717 | Player_A |
| 30829 | Player_B |
| 30893 | Player_C |
| 30657 | Player_D |
The task is to get the MAX(overall_rating) of each year and the player_name associated with it via the player_api_id. The following code:
WITH CTEMax_Rating AS(
SELECT SUBSTRING(date,0,5) AS Thedate,
MAX(overall_rating) AS MaxRating
FROM Player_Attributes
GROUP BY SUBSTRING(date,0,5)
)
SELECT PAT.player_api_id, CTEMax_Rating.MaxRating,
CTEMax_Rating.Thedate, PYR.player_name
FROM CTEMax_Rating
INNER JOIN
Player_Attributes AS PAT
ON
CTEMax_Rating.MaxRating = PAT.overall_rating
AND
CTEMax_Rating.Thedate = SUBSTRING(PAT.date,0,5)
INNER JOIN
Player AS PYR
ON
PAT.player_api_id = PYR.player_api_id
ORDER BY CTEMax_Rating.Thedate
Gives this output:
player_api_id | overall_rating | date | player_name
30717 | 93 | '2007' | Player_A
30829 | 93 | '2007' | Player_B
30893 | 91 | '2008' | Player_C
30657 | 91 | '2008' | Player_D
30657 | 91 | '2009' | Player_D
The thing is, how can I tweak the code to return a single occurrence since some players are tied with a MAX(overall_rating)?
The output I'd like is something like this:
player_api_id | overall_rating | date | player_name
30717 | 93 | '2007' | Player_A
30893 | 91 | '2008' | Player_C
30657 | 91 | '2009' | Player_D
Thanks in advance.