Correlated Subquery Top N Per Group

Find the top N rows per group using a correlated subquery with a count of better rows for ranking.

SqlData Fetching

Code

sqlsnippet
9 lines
SELECT department, employee_name, salary
FROM employees e1
WHERE (
  SELECT COUNT(*)
  FROM employees e2
  WHERE e2.department = e1.department
    AND e2.salary > e1.salary
) < 3
ORDER BY department, salary DESC;

What the code does

At its core this is a single SELECT statement against employees.

Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation; an ORDER BY that fixes the output order.

Applying it

Point it at the employees table.

Statements that matter

SELECT department, employee_name, salary
FROM employees e1
WHERE (
  SELECT COUNT(*)
  FROM employees e2
  WHERE e2.department = e1.department
    AND e2.salary > e1.salary
) < 3
ORDER BY department, salary DESC;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `employees`.