我想从表中每个部门的部门编号,工资和其他各个栏目中找到两个最高工资。我得到了这个答案;它肯定有效,但我无法理解逻辑。无法理解查询
select *
from emp a where 2 > (select count(distinct(sal))
from emp
where sal > a.sal and a.deptno=deptno)
order by deptno;
我想从表中每个部门的部门编号,工资和其他各个栏目中找到两个最高工资。我得到了这个答案;它肯定有效,但我无法理解逻辑。无法理解查询
select *
from emp a where 2 > (select count(distinct(sal))
from emp
where sal > a.sal and a.deptno=deptno)
order by deptno;
对于员工的每一行,WHERE子句数有多少行具有在同一个部门有较高的收入中查询。然后,WHERE子句本身将结果限制为仅具有1或0行(2 >
)在同一个部门的工资更高的工资 - 即最高的两个工资。
所以用这个数据:
EmployeeId Sal DeptNo No. of rows in the same department with higher salary
1 1 1 3 (employees 2, 3 and 4)
2 2 1 2 (employees 3 and 4)
3 3 1 1 (employee 4)
4 4 1 0
5 1 2 2 (employees 6 and 7)
6 2 2 1 (employee 7)
7 3 2 0
...查询将选择员工3,4,6,7,因为他们是员工少于2名员工谁拥有更高的薪水比他们。
inner select返回给定员工的同一个部门中较高薪水的数量。现在,如果同一部门内的薪水不足两个,那么给定的员工必须是部门内最高收入或次高收入人员。
重新定位子查询到SELECT
条款没有“顶部2”限制(显然会得到更多的行回):
select a.*,
(
select count(distinct(sal))
from emp
where sal > a.sal and a.deptno=deptno
) as tally
from emp a
可以使用一个WHERE
子句引入另一层次例如然后限制结果集
select b.*
from (
select a.*,
(
select count(distinct(sal))
from emp
where sal > a.sal and a.deptno=deptno
) as tally
from emp a
) b
where b.tally < 2
order
by b.deptno, b.tally;
上面是更详细的,但也许更容易遵循的逻辑。
绝对..只要你需要在两个部分发起查询...顺便谢谢 – Birju
好吧,我不会提供我的回复...非常相似! – Cris
其中'谁是谁是最快的答案按钮'问题:) –
+1哦补了我写了这样一个很好的答案,太慢了:) – Mattis