简体   繁体   English

仅选择一个字段的最大值,并按另一字段分组的行

[英]Selecting only rows with the highest value of one field, grouped by another field

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. 我花了太多时间试图解决这个问题。

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: 如果需要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. 编辑:对不起,这是一个SQL解决方案...只是看到了MSACCESS标记。 Logic is right, but you'll need to convert to access syntax. 逻辑是正确的,但是您需要转换为访问语法。

edit to correct the second query, missed a column inh my join 编辑以更正第二个查询,错过了我加入的列

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 选择字段中字段值最高的数据 - selecting data with highest field value in a field 如何对一个ID字段进行分组并选择另一个字段中具有最高值的行PostgreSQL - how to group an ID field and select rows having highest value in another field PostgreSQL SQL检索与最高日期匹配的ID(按另一个字段分组) - SQL to retrieve id that match the highest date, grouped by another field 从表中选择一个字段具有相同值的行 - Selecting rows from a table that have the same value for one field "在选择不同行时按一个字段中的最小值分组" - Group by minimum value in one field while selecting distinct rows 选择一个字段包含相同值的所有行 - Selecting all rows where one field contains the same value SQL 返回给定字段具有最高值的行 - SQL Return rows with highest value for a given field 选择列中只有一个值且具有另一个公用值的所有行 - Selecting all rows with only one value in column with another common value Mysql:获取具有按字段分组的最大值的行 - Mysql: Get the rows with max value grouped by a field SQL-如果一个字段只是一个特定值并且不作为另一个值存在,则仅需要按记录分组 - SQL - Only want a Grouped by record if a field is only a specific value and does not exist as another value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM