Top Salaries per DepartmentHard

Top Salaries per Department

HardSQLPractice library · +30 XPwindow functionsrankingsql

The employees table lists who works where and what they earn.

Return the employees who have one of the two highest distinct salaries in their department. People who earn the same amount share a rank, so a department can return more than two people. Departments with fewer than two distinct salaries return everyone.

Return department, name and salary, ordered by department, then salary from high to low, then name.

Tables

CREATE TABLE employees (
  id serial PRIMARY KEY,
  name text NOT NULL,
  department text NOT NULL,
  salary integer NOT NULL
);

Example data

INSERT INTO employees (name, department, salary) VALUES ('Asha','Engineering',9500),('Ravi','Engineering',9000),('Kim','Engineering',8000),('Maya','Sales',7000),('Omar','Sales',6500);

Your query is also checked on hidden datasets with different data.

Hints