Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 Script Library
 Very simple sql query
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

1 Posts

Posted - 02/22/2011 :  12:54:28  Show Profile  Reply with Quote
I have a table:
UserId, UserGroup, ConnectionsNumber
UserId is unique but UserGroup could be repeated.
As an example, the table is filled like this:
1 1 3
2 1 4
3 1 5
4 2 1
5 3 10
I need to select only 1 record per user group and it must have the maximum connectionNumber
If I do it like this:
select UserGroup, UserId, max(connectionsNumber)
from table
group by UserGroup, UserId
then I get several records...
And If I select select UserGroup, max(connectionsNumber)
from table
group by UserGroup
then it's fine but I'm missing UserId field...
Please correct my query, I know it must be very simple

Flowing Fount of Yak Knowledge

2875 Posts

Posted - 02/22/2011 :  14:13:54  Show Profile  Reply with Quote
You should post in the New to SQL forum, you might get overlooked here

I am assuming you're on 2005 or later
select userid,usergroup, ConnectionsNumber
,[rank] = rank() over(partition by usergroup order by ConnectionsNumber desc)
from yourTable
) a

WHERE [rank] = 1


Everyday I learn something that somebody else already knew
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2019 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000