Skip to content
Advertisement

Select Max Value from a set of values with the same id

I have these two tables:

CREATE TABLE Category (

CategoryID int NOT NULL,
CategoryName varchar(255),

PRIMARY KEY (CategoryID)
);

CREATE TABLE Team (

CategoryID int NOT NULL,
TeamName varchar(255) NOT NULL,
Points int(255),

PRIMARY KEY (TeamName),
FOREIGN KEY (CategoryID) REFERENCES Category(CategoryID)
);

I want to find the team with the most points from every category.

So far i have tried these, i know they are wrong, but im on dead-end. Any advice will be helpful.

SELECT category.categoryid, team.teamname, MAX(team.points)
FROM category, team
GROUP BY team.teamname
HAVING MAX(team.points);


select category.categoryid, team.teamname
from category
right join team on team.categoryid = category.categoryid
group by team.teamname
having max(team.points);


select team.categoryid, team.teamname
from team, team a
having max(team.points);


select category.categoryid, team.teamname, max(team.points), team.points
from team
inner join category on category.categoryid = team.categoryid
group by teamname
having (select distinct max(team.points) from team);


select category.categoryid, team.teamname, team.points
from team
inner join category on category.categoryid = team.categoryid;

Advertisement

Answer

I want to find the team with the most points from every category.

WITH cte AS ( SELECT *, RANK() OVER (PARTITION BY CategoryID ORDER BY Team.Points DESC) rnk
              FROM Category 
              NATURAL JOIN Team )
SELECT *
FROM cte
WHERE rnk = 1

But if there is more then one team in a category with the same maximal points then all of them will be returned.

If you need only one of them in this case, then additional ordering needed (and it must provide rows uniqueness). For example, it can be

WITH cte AS ( SELECT *, RANK() OVER (PARTITION BY CategoryID ORDER BY Team.Points DESC, Team.TeamName) rnk
              FROM Category 
              NATURAL JOIN Team )
SELECT *
FROM cte
WHERE rnk = 1;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5c73ac6a99e270535c70b173a65c02ff

Of course you may select only needed columns< i.e. SELECT CategoryName, TeamName.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement