2015-04-07 67 views
0

匹配骨料我做了一個非常簡單的樣品 http://sqlfiddle.com/#!6/d2cc0/4T-SQL獲得該組由

我有一個表「人」有一個名字,年齡和體重列。我想檢索每個年齡段最輕的人的名字。

我按年齡分組人數,所以我可以在每個不同年齡都檢索最輕的人的體重,但是我怎樣才能獲得與min()聚合匹配的名字?

回答

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

使用分區:

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) 

注意,如果有關係都將每個年齡返回不止一個人。