Tuesday, June 19, 2012

WITH TIES in sql server

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 TOPclause:

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


Which gives:

NameScore
Brenda42
Maureen41
Edwin41
Terry40
Rupert39
Arthur39
Paula39

No comments:

Post a Comment