Selecting only rows with the highest value of one

2019-09-03 14:41发布

问题:

I have a table that has information structured like this:

ID  Points  Name    School
1   123     James   A
2   534     Henry   B
3   56      Henry   B
4   153     Chris   B
5   95      Chris   B
6   83      Chris   B
7   421     James   A

And I need to get out of a query the rows that have the same name, but only the highest points for each like this:

ID  Points  Name    School
7   421     James   A
2   534     Henry   B
4   153     Chris   B

Any ideas on how this could be accomplished with a query? I've spent way too much time trying to figure this out.

回答1:

select name,school,max(points) from table group by name,school

That will give you the max points per name/school combination. Join it to itself if you want the ID:

select table.* from table inner join
(select name,school,max(points) as points from table group by name,school) a
on a.name = table.name and a.school = b.school and a.points = table.points

edit : sorry, this is a SQL solution...just saw the MSACCESS tag. Logic is right, but you'll need to convert to access syntax.

edit to correct the second query, missed a column inh my join



回答2:

SELECT 
    (SELECT TOP 1 ID FROM Table 
    WHERE 
        Name = t.Name AND 
        School=t.School AND 
        Points=t.Points
    ) as Id, t.Name, t.Points, t.School
FROM 
    (SELECT Name, School, max(Points) as Points
    FROM Table
    GROUP BY Name, School) t