I need to find the highest score for each game. along with the gamename, category, PlayerCode (name of player) who got the highscore, date (time) when the score was set and ofc the score itself.
My tables are set up as follows
CREATE TABLE Player(
PlayerId INT,
Date DATE,
PlayerCode CHAR(3),
PRIMARY KEY (PlayerId)
);
CREATE TABLE Game(
GameId INT,
Name VARCHAR(128),
Description VARCHAR(256),
Launched DATE,
Category ENUM('Adventure', 'Action', 'RPG', 'Simulation', 'Sports', 'Puzzle', 'Other'),
PRIMARY KEY (GameId)
);
CREATE TABLE Results(
PlayerId INT,
GameId INT,
Time DATETIME,
Score INT,
PRIMARY KEY (PlayerId,GameId,Time),
CONSTRAINT ResultsGameFK FOREIGN KEY (GameId) REFERENCES Game (GameId),
CONSTRAINT ResultsPlayerFK FOREIGN KEY (PlayerId) REFERENCES Player (PlayerId)
);
So far i can i can only get each score for each player in each game. When the top score in each game is what im looking after. I only recently learned about joins, but this one has me confused. Thank you
Select Game.Name, Game.Category, PlayerCode, Score, Time
from Player
JOIN Results
ON Player.PlayerId = Results.PlayerId
JOIN Game
ON Game.GameId = Results.GameId
group by Game.Name, Game.Category, Score, PlayerCode, Time
order by Score DESC
3
Answers
You have almost done that. you have already applied GROUP BY clause, it means you can perform aggregation.
In your select clause do this
By MAX(Score), you can get greatest score, and you have already ORDER BY score DESC, that means you will get highr score first.
Ideally you would use RANK, but if that’s not available (for example you have an older database version), a solution that allows multiple players to tie a highscore can be written:
If you can use RANK, and having more than one highscore is acceptable (i.e. for ties), try:
If you must have at most one result per game, change the RANK to:
The logic there is the player with the highest, earliest, score gets the high score. (…breaking the tie by the player ID if those are the same — this may not be what you want — adapt as required)
Note I changed a couple of your column names to avoid clashes with SQL keywords (
Time
,Date
).There you go:
Will give you the highest score for each game in your dataset:
EDIT:
if you don’t mind the ties and the many subqueries then this includes the player: