简体   繁体   中英

select max element columns from group

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() can 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM