我有点问题。这是一个代码:
select * from
(select department_id, manager_id,last_name, salary, row_number() over
(partition by department_id,manager_id order by salary asc) p_number
from employees )
where p_number <=3;
此查询显示部门中每位经理的每个部门的工资最少3 例如:Dep no.30有2名经理(100和114),经理100号有1名员工,经理114号 - 3名员工。
结果的一部分:
20 100 Hartstein 13000 1
20 201 Fay 6000 1
30 100 Raphaely 11000 1
30 114 Colmenares 2500 1
30 114 Himuro 2600 2
30 114 Tobias 2800 3
现在,我想删除所有行,其中只有1名员工在经理下面。在这个例子中应该有,Harstein,Fay,Raphaely。 Colmenares也排名第一,但经理114下有更多员工。 有任何想法吗? PS有计数出局,因为没有组,并且修改
where p_number <=3;
进入
where p_number <=3 and p_number >1;
也出局了,因为它会删除我的所有1号员工,我想'安全'少,因为他们有更多'同事':) 谢谢!
答案 0 :(得分:0)
这将给出结果,只需要一次表扫描:
SELECT *
FROM (
SELECT department_id,
manager_id,
last_name,
salary,
ROW_NUMBER()
OVER ( PARTITION BY department_id, manager_id
ORDER BY salary ASC ) AS p_number,
COUNT(*)
OVER ( PARTITION BY department_id, manager_id ) AS p_count
FROM employees
ORDER BY department_id, manager_id, salary
)
WHERE p_count >= 2
AND p_number <= 3;
<强>输出强>:
DEPARTMENT_ID MANAGER_ID LAST_NAME SALARY P_NUMBER P_COUNT
------------- ---------- ---------- ---------- ---------- ----------
30 114 Colmenares 2500 1 3
30 114 Himuro 2600 2 3
30 114 Tobias 2800 3 3