简体   繁体   中英

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;

Version 8.0 supports dense_rank()

SELECT teamname
FROM (
    SELECT categoryid, teamname,
       dense_rank() over(partition by categoryid order by points desc) rnk
    FROM team
)t
WHERE rnk = 1
GROUP BY teamname
HAVING count(*) = (SELECT count(*) FROM Category);

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< ie SELECT CategoryName, TeamName .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM