I have a SCORE column. How do I select the top 10% from EMPLOYEE table with top scores?
You could do it with analytics. Assuming that score is ascending (higher scores are better):
SELECT e.*
FROM (SELECT e.*,
row_number() OVER (ORDER BY score DESC)
/ COUNT(*) OVER () pct
FROM employee e) e
WHERE pct <= 0.1
This will select at most 10% of your employees. If there are equal scores among them, the above SQL will pick among them in a non-deterministic fashion. If you want to include all those that are in the top 10% including duplicate scores, replace row_number()
by rank()
.
You could also use the NTILE
function:
SELECT e.*
FROM (SELECT e.*,
ntile(10) OVER (order by score DESC) ntile#
FROM employee e) e
WHERE ntile# = 1