T-SQL 获取与 group by 中的聚合匹配的列
T-SQL get column that matches aggregate in group by
我做了一个非常简单的示例
http://sqlfiddle.com/#!6/d2cc0/4
我有一个 table "People" 有名字、年龄和体重。我想检索每个年龄段最轻的人的名字。
我按年龄对人进行分组,这样我就可以检索每个不同年龄段最轻的人的体重,但是如何检索与 min() 聚合匹配的姓名?
以下查询将 return 姓名、年龄和最小体重:
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 |
使用分区:
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)
请注意,如果有关系,两者将 return 每个年龄段的人都不止一个。
我做了一个非常简单的示例 http://sqlfiddle.com/#!6/d2cc0/4
我有一个 table "People" 有名字、年龄和体重。我想检索每个年龄段最轻的人的名字。
我按年龄对人进行分组,这样我就可以检索每个不同年龄段最轻的人的体重,但是如何检索与 min() 聚合匹配的姓名?
以下查询将 return 姓名、年龄和最小体重:
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 |
使用分区:
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)
请注意,如果有关系,两者将 return 每个年龄段的人都不止一个。