Return name, departmentid, salary of employees in the top 10 percent of salary WITHIN their department (PERCENTRANK =…
SQLLevel: IntermediateRanking and Top-N
Return name, department_id, salary of employees in the top 10 percent of salary WITHIN their department (PERCENT_RANK >= 0.9).
Table definitions (from the source exercise):
CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: PERCENT_RANK() OVER (PARTITION BY dept ORDER BY salary) in a subquery; filter outside.
SELECT name, department_id, salary
FROM (
SELECT e.*, PERCENT_RANK() OVER (PARTITION BY department_id
ORDER BY salary) AS pr
FROM employees e
) x
WHERE pr >= 0.9;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT