获得3个最高工资的查询说明

Sai*_*Sai 2 sql oracle

任何人都可以解释以下查询获得3个最高薪水吗?

select distinct sal
  from emp a
where 3 >= (select count(distinct sal)
              from emp b
            where a.sal <= b.sal)
order by a.sal desc;
Run Code Online (Sandbox Code Playgroud)

有人建议我使用上面的查询来获得3个最大值.表中的工资.我不明白查询的下面部分发生了什么:

3>= (select count(distinct sal)
       from emp b
     where a.sal <= b.sal) ;
Run Code Online (Sandbox Code Playgroud)

有人能解释一下吗?如果还有其他方法可以得到相同的结果,请咨询我

Gau*_*oni 7

   empid    sal
   ===============
    1       300
    2        50
    3       400
    4       200
    5       150
   ================

select distinct sal from emp a where 3        --outer query
  >=
 (select count(distinct sal) from emp b             --inner query(correlated)
        where a.sal <= b.sal) order by a.sal desc;
Run Code Online (Sandbox Code Playgroud)
  1. 它从外部查询中获取所有记录,即emp a,并逐个迭代,将值传递给内部查询
  2. 让我们举个例子
  3. 它获取第一条记录,即1和300,并将此值传递给内部查询
  4. 内部查询尝试查找小于或等于emp表b中记录的不同sal
  5. 计数为3,因为50,200,150小于300,并且由于3> = 3(来自内部查询),答案为真,并且选择了300.
  6. 现在外循环计数器到达第二行,即2和50,它传递值并检查内在查​​询,然后计数不满足3> =标准,因此未选择50.
  7. 现在400,在这种情况下内部查询返回4并因此满足标准,因此选择400
  8. 现在200,在这种情况下内部查询重新开始3,因此也选择了这个
  9. 现在150,在这种情况下内部查询返回2,因此这已被过滤掉
  10. 因此结果将是400,300,200被选中.