Design a query to simulate the RANK() function without using window functions.
Instruction: Using PostgreSQL employees(id integer PRIMARY KEY, department_id integer, salary numeric NOT NULL), reproduce RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) without window functions. Treat NULL department IDs as one partition and explain tied salaries.
Updated
Official answer
For each employee, count employees in the same department with a strictly higher salary, then add one. Counting rows rather than distinct salaries reproduces RANK's gaps after ties.
Assume PostgreSQL employees(id integer PRIMARY KEY, department_id integer, salary numeric NOT NULL):
SELECT e.id, e.department_id, e.salary,
1 + (SELECT COUNT(*)
FROM employees AS higher
WHERE higher.department_id IS NOT DISTINCT FROM e.department_id
AND higher.salary > e.salary) AS salary_rank
FROM employees AS e
ORDER BY e.department_id NULLS LAST, e.salary DESC, e.id;
Department salaries 100, 100, 90 receive ranks 1, 1, 3. Another department starts independently at 1. The NULL-safe department comparison treats missing department IDs as one partition, matching the stated policy. Salaries are explicitly non-NULL here.
The employee ID only orders displayed ties; it is absent from the rank comparison. DENSE_RANK would count distinct higher salaries. Check duplicate salaries, separate departments, singleton and empty inputs. A correlated count can be expensive; prefer the window function when available and validate plans on real workloads.