harriyott.com

Tuesday, June 05, 2007

With Ties - SQL Server Tip

Consider the following table of data from my database:

NameScore
Brenda42
Maureen41
Edwin41
Terry40
Rupert39
Arthur39
Paula39
Eric38


These are my fictional students from my fictional cooking class, with their fictional scores from my fictional washing-up exam.

Suppose I wanted to find the top five students. I would do a SELECT TOP 5 statement, thus:

SELECT TOP 5 Name, Score
FROM Scores
ORDER BY Score DESC


This results in the following:

NameScore
Brenda42
Maureen41
Edwin41
Terry40
Rupert39


Note that although there are 3 students with a score of 39, only Rupert made it onto the top 5. To get Arthur and Paula too, then one can use WITH TIES as part of the TOP clause:

SELECT TOP 5 WITH TIES Name, Score
FROM Scores
ORDER BY Score DESC


Which gives:

NameScore
Brenda42
Maureen41
Edwin41
Terry40
Rupert39
Arthur39
Paula39


I only found this one out today. Interesting.

[Tags: ]

1 Comments:

Jane said...

Cool - I didn't know that either :-)

June 06, 2007 6:13 PM  

Post a Comment

Links to this post:

Create a Link

<< Home