简体   繁体   中英

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.

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.

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:

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
        );

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