我在谷歌搜索中找到了以下解决方案,但我无法理解。谁能解释这个查询是如何处理的。
SELECT *
FROM employee_test e1
WHERE 3 = (SELECT DISTINCT count(*)
FROM employee_test e2
WHERE e2.emp_sal > e1.emp_sal)
我在谷歌搜索中找到了以下解决方案,但我无法理解。谁能解释这个查询是如何处理的。
SELECT *
FROM employee_test e1
WHERE 3 = (SELECT DISTINCT count(*)
FROM employee_test e2
WHERE e2.emp_sal > e1.emp_sal)
It's a very inefficient correlated query to return the employee with the 4th highest salary.
SELECT *
FROM employee_test e1
WHERE 3 = (SELECT DISTINCT count(*)
FROM employee_test e2
WHERE e2.emp_sal > e1.emp_sal);
Assuming salaries (emp_sal) are unique, the subquery counts how many employees have a higher salary than the employee in 'e1'. If the count is 3, then this is the employee with the 4th highest salary.
If there is a tie for 4th (e.g. through 6th or 10th), all the ties will be shown in the result. If there is a tie that involves the 4th and one higher slot, e.g. 2nd to 4th or 3rd and 4th, then there will be no results, since NO value of emp_sal has EXACTLY 3 records with higher emp_sal values.
The better form would be
select top(1) with ties *
from (
select *, rn=rank() over (order by emp_sal desc)
from employee_test
) x
where rn <= 4
order by rn desc;
This shows the outright 4th highest salary (and ties if any), or if there is a tie across persons 3rd through 6th (covering spot #4), it will show 3rd through 6th.