计算没有分组的列值的组函数(count,min,max ...)

Vla*_*aya 3 mysql sql group-by

假设我有一张下表:

表用户(id,姓名,年龄,城市)

1 John    26 New York
2 Aaron   31 Dallas
3 Jenifer 35 Dallas
4 Connely 34 New York
Run Code Online (Sandbox Code Playgroud)

我希望有一个表格,所有用户的最小用户年龄都是他(她)的城市:

1 John    26 New York 26
2 Aaron   31 Dallas   31
3 Jenifer 35 Dallas   31
4 Connely 34 New York 26
Run Code Online (Sandbox Code Playgroud)

这个例子有点人为,但我没有弄清楚任何更好的简短例子.

如果我使用的请求如下:

SELECT*FROM users MIN(年龄)GROUP BY city

我可能会得到:

1 John    26 New York
2 Aaron   31 Dallas
Run Code Online (Sandbox Code Playgroud)

我不确定它会返回第1行和第2行,但这不是重点:我需要在结果中包含所有用户.

可能吗?

Gor*_*off 11

我倾向于这样做join:

select u.*, c.minage
from users u join
     (select city, min(age) as minage
      from users
      group by city
     ) c
     on u.city = c.city;
Run Code Online (Sandbox Code Playgroud)

  • @Calvintwr..."左连接"是不必要的,因为聚合中的所有城市都在表格中(如果"城市"为"空",则"左连接"不会完全按照您的意愿行事).如果你想要明确,那么你可以编写`inner join`. (2认同)