I have two questions:
When using the
select top 10 percent
statement, for example on a test database with 100 scores, like this:Select top 10 percent score from test
Would SQL Server return the 10 highest scores, or just the top 10 obs based on how the data look like now (e.g. if the data is entered into database in a way that lowest score appears first, then would this return the lowest 10 scores)?
I want to be able to get the top 10 highest scores and bottom 10 lowest scores out of this 100 scores, what should I do?
Using a
UNION ALL
means that it will count all rows twice.You can do it with a single count as below. Whether or not this will be more efficient will depend (e.g. on indexes).
You could also use the
NTILE
window function to group your scores into 10 groups of data - group no. 1 would be the lowest 10%, group no. 10 would be the top 10%:if duplicates are allowed use union
Use ascending in your query for the top 90. Then, descending in your query for the top 10. Then, union these two queries