我制作了一个非常简单的样本 http://sqlfiddle.com/#!6/d2cc0/4
我有一张桌子"人们"名字,年龄和体重。我想要了解每个年龄段最轻的人的名字。
我按年龄对人进行分组,这样我可以在每个不同的年龄检查最轻的人的体重,但我怎样才能找到与min()聚合相匹配的名字?
答案 0 :(得分:1)
以下查询将返回姓名,年龄和最小体重:
SELECT P.* from People P JOIN (SELECT
age,
min(weight) as lightest
FROM
People
GROUP BY age) T on p.age = T.age and p.weight = T.lightest
| name | age | weight |
|------|-----|--------|
| A | 20 | 60 |
| C | 25 | 70 |
答案 1 :(得分:1)
使用分区:
Select * from (
Select *
, min(weight) over (partition by age) as MinWeight
from People) a
where Weight = MinWeight
或:
Select * from people a
where weight = (select min(weight) from people b where a.age = b.age)
请注意,如果有关系,两个人每个年龄都会返回多个人。