开发者

select max element columns from group

开发者 https://www.devze.com 2023-04-06 19:07 出处:网络
I\'d like to select the maximum row of a group, but I\'d like the query to return the other columns from that row. I know how MAX() ca开发者_Python百科n return the greatest integer in the group, but I

I'd like to select the maximum row of a group, but I'd like the query to return the other columns from that row. I know how MAX() ca开发者_Python百科n return the greatest integer in the group, but I don't know how to get the other columns for the max result.

In this example, I'd like to have a query that selects the maximum userId from each group but returns the userId and Name

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

I'd like the output of the query to be

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

I know I could do

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

and then do a subquery again on users. I'm just looking to see if there is a better way.

If it matters, I'm using MySQL


Try this

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
0

精彩评论

暂无评论...
验证码 换一张
取 消