获取按一些列排序的每个组的一条记录

时间:2015-01-18 13:30:01

标签: mysql

鉴于下表:

id, country,  name, age
 1,  Italy,  Burke,  21
 2,  Italy, Yefrem,  20
 3,  Spain, Valter,  30
 4,  Spain,    Max,  11

我怎样才能为每个国家找到一个最老的公民 例如,结果应仅包含行13

结果应按国家/地区分组,并且每个组中应返回年龄最大的条目

1 个答案:

答案 0 :(得分:2)

使用内联视图过滤行,然后连接到表本身以获取所有列,如下所示:

select t.id, t.country, t.name, t.age
from test t
join (
  select max(age) as age, country
  from test
  group by country
) s
on t.age = s.age and t.country = s.country;

在这里测试:http://sqlfiddle.com/#!2/2523ce/3

相关问题