[英]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.