Find the bugs: Second-highest salary in each department
For every department in the department table, find the second-highest distinct salary. If two employees share the highest salary, for example, the next lower amount counts as the second-highest salary. Include departments with no second distinct salary, returning NULL for them. The result must contain exactly one row per department. Find the lines containing errors.
Find the errorsDuplicates and top NSeniorAnalystData Engineer
Input data · iv_employees
| id | name | department_id | manager_id | salary | hired_at |
|---|---|---|---|---|---|
| 1 | Anna | 1 | NULL | 5000.00 | 2020-03-01 09:00:00 |
| 2 | Boris | 1 | 1 | 5000.00 | 2021-06-15 09:00:00 |
| 3 | Clara | 1 | 1 | 4000.00 | 2022-01-31 23:59:00 |
| 4 | Dmitry | 2 | 1 | 6000.00 | 2019-09-01 09:00:00 |
| 5 | Elena | 2 | 4 | 5500.00 | 2021-02-01 00:00:00 |
| 6 | Foma | 2 | 4 | 5500.00 | 2023-04-10 10:30:00 |
| 7 | Galina | 3 | 1 | 4500.00 | 2020-11-20 09:00:00 |
| 8 | Hugo | NULL | 1 | 3000.00 | 2024-05-05 09:00:00 |
| 9 | Irina | 3 | 7 | NULL | 2024-08-12 09:00:00 |
| 10 | Egor | 2 | 4 | 3500.00 | 2025-01-13 09:00:00 |
Input data · iv_departments
| id | name |
|---|---|
| 1 | Sales |
| 2 | Engineering |
| 3 | Analytics |
| 4 | Legal |
SELECT DISTINCT d.id, d.name, t.salary AS second_salary
FROM iv_departments d
LEFT JOIN (
SELECT department_id, salary,
RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) AS pos
FROM iv_employees
WHERE salary IS NOT NULL
) t ON t.department_id = d.id
WHERE t.pos = 2
ORDER BY d.id