SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

sqlreader
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

jimf
Flowing Fount of Yak Knowledge

USA
2869 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 *
FROM
(
select userid,usergroup, ConnectionsNumber
,[rank] = rank() over(partition by usergroup order by ConnectionsNumber desc)
from yourTable
) a

WHERE [rank] = 1


Jim

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