Top 3 distinct salaries per department (top N per group)
MediumP1Coding
Tables:
department
| Column | Type |
|---|---|
| id | int (primary key) |
| name | text |
employee
| Column | Type |
|---|---|
| id | int (primary key) |
| name | text |
| salary | int |
| department_id | int (references department.id) |
Write a query that returns the employees who earn one of the top three distinct salaries in their department. If several employees share a salary, all of them are returned. Return the columns department (the department name), employee and salary.
Schema
CREATE TABLE department ( id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE employee ( id int PRIMARY KEY, name text NOT NULL, salary int NOT NULL, department_id int NOT NULL REFERENCES department(id) );
Example 1
- Input
- department: (1, 'IT') employee: (1, 'A', 100, 1), (2, 'B', 100, 1), (3, 'C', 90, 1), (4, 'D', 80, 1), (5, 'E', 70, 1)
- Output
- IT, A, 100 IT, B, 100 IT, C, 90 IT, D, 80
- Why
- The distinct salaries are 100, 90, 80, 70. The top three are 100, 90 and 80, so E is out.
Constraints
- PostgreSQL dialect.
- "Top three" counts distinct salary values, not people.
- Return rows in any order.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
PostgreSQL
Run checks the 2 visible tests, Submit all 5. ⌘Enter runs, ⌘⇧Enter submits.