从组中选择最大元素列

时间:2011-09-22 00:54:59

标签: mysql sql

我想选择组的最大行,但我希望查询返回该行的其他列。我知道MAX()如何返回组中的最大整数,但我不知道如何获得最大结果的其他列。

在此示例中,我想要一个查询,从每个userId中选择最大group但返回userId和Name

Users
groupId | userId | name
----------------------
1       | 1      | mike
1       | 2      | dave
2       | 3      | bill
2       | 4      | steve

我希望查询的输出为

groupId | userId | name
-----------------------
1       | 2      | dave
2       | 4      | steve  

我知道我能做到

select groupId, max(userId)
from Users
group by groupId;

然后再次对用户执行子查询。我只是想看看是否有更好的方法。

如果重要,我正在使用MySQL

1 个答案:

答案 0 :(得分:3)

试试这个

select * from users
join (select groupId, max(userId) as maxU from Users group by groupId) xx
on xx.groupId=users.groupId and users.userId=xx.maxU
相关问题