简体   繁体   English

如何为一组记录中的每个记录选择带有大号X的记录

[英]How do I select the record with the largets X for each of a group of records

Let's say I have the following table: 假设我有下表:

First_Name    Last_Name    Age
John          Smith        50
Jane          Smith        40
Bill          Smith        12
Freda         Jones        30
Fred          Jones        35
David         Williams     50
Sally         Williams     20
Peter         Williams     35

How do I design a query that will give me the first name, last name and age of the oldest in each family? 如何设计一个查询,让我知道每个家庭中年龄最大的名字,姓氏和年龄? It must be possible but it's driving me nuts. 一定有可能,但这让我发疯。

I'm looking for a general SQL solution, although I've tagged ms-access as that is what I am actually using. 我正在寻找一种通用的SQL解决方案,尽管我已将ms-access标记为,因为这是我实际使用的方法。

SELECT t1.First_Name, t1.Last_Name, t1.Age
FROM family t1
INNER JOIN
(
    SELECT Last_Name, MAX(Age) AS maxAge
    FROM family
    GROUP BY Last_Name
) t2
    ON t1.Last_Name = t2.Last_Name AND t1.Age = t2.maxAge

Note: This will give multiple records per family in the event of a tie. 注意:如果发生平局,这将为每个家庭提供多个记录。

Simple answer, do a correlated sub-select to get the "current" families highest age: 简单的答案,做一个相关的子选择以获得“当前”家庭的最高年龄:

select *
from tablename t1
where t1.Age = (select max(t2.Age) from tablename t2
                where t2.Last_Name = t1.Last_Name)

However, Tim Biegeleisen's query is probably a bit faster. 但是,Tim Biegeleisen的查询可能要快一些。

I tend to use NOT EXISTS in situations like this, as many DBMS are able to use an anti semi-join in this case, which can lead to better performance: 我倾向于在这种情况下使用NOT EXISTS ,因为许多DBMS在这种情况下都可以使用反半联接,这可以导致更好的性能:

SELECT  *
FROM    Table AS t
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    Table AS t2
            WHERE   t2.Last_Name = t.Last_Name
            AND     t2.Age > t.Age
        );

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

相关问题 SQL问题:如何在每个记录组中选择任意数量的记录? - SQL question: how to select arbitrary numbers of records in each record group? 如何为每个子记录选择特定记录? - How do you select specific records for each sub record? 如何从一个表中为另一个表中的每个唯一记录选择 100 条记录 - How do I select 100 records from one table for each unique record from another 如何根据多个字段的分组更新表中的记录和每个组的第一个记录 select? - How to update records in table based on group by on multiple fields and select first record from each group? 按值查询选择记录值占各组记录总值的百分比 - Query select record value as % of total records value for each group by value 如何为每个组选择随机记录 - How to select a random record for each group 我如何 select 记录计数,然后按外键对它们进行分组? - How do I select the count of records, then group them by a foreign key? 使用MAX()和GROUP BY时如何选择整个记录 - How Do I Select the Entire Record When Using MAX() With GROUP BY 即使表中没有记录,如何获取 SQL 中每个组的记录? - How to get a record for each group in SQL even when there are no records in the table? 根据组中的一条记录选择一组记录 - Select a group of records based on one record in the group
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM