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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Select Top Score or Winners of game
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

ConfusedAgain
Yak Posting Veteran

United Kingdom
81 Posts

Posted - 05/02/2012 :  05:39:11  Show Profile  Reply with Quote
I have a table that records the scores of players in a game. I want to create a statement that picks the winner.

SELECT Top(1) [GameID]
,[PlayerUserName]
,[PlayerScore]
FROM [Players]
ORDER BY PlayerScore

This would work however if there are two players with the same score I need to select both of them as winners. How can I do this?

Thanks

webfred
Flowing Fount of Yak Knowledge

Germany
8515 Posts

Posted - 05/02/2012 :  06:15:16  Show Profile  Visit webfred's Homepage  Reply with Quote
select ...
from Players
where PlayerScore = (select max(PlayerScore) from Players)



No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 05/02/2012 :  07:06:01  Show Profile  Reply with Quote
You can also use WITH TIES keyword
SELECT Top(1) WITH TIES [GameID]
,[PlayerUserName]
,[PlayerScore]
FROM [Players]
ORDER BY PlayerScore
Unless this is golf, you may want to add a DESC keyword in the order by clause (to pick the highest score rather than the lowest).
Go to Top of Page

ConfusedAgain
Yak Posting Veteran

United Kingdom
81 Posts

Posted - 05/02/2012 :  07:14:43  Show Profile  Reply with Quote
Many thanks for that.
Go to Top of Page

denis_the_thief
Constraint Violating Yak Guru

Canada
470 Posts

Posted - 05/02/2012 :  10:20:12  Show Profile  Reply with Quote
Another option:

select * from
	(
	SELECT 
	*, RANK() OVER (ORDER BY PlayerScore) [rank]
	from Players
	) T
where [RANK] = 1
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.06 seconds. Powered By: Snitz Forums 2000