(2)在下面的SQL查询中的含义是什么

时间:2017-08-20 05:46:56

标签: sql oracle

有人请解释为什么2用于以下查询。

select * from employee e 
where(2) = (select count(distinct(e1.sal))
            from employee e1
            where e.sal > e1.sal);

2 个答案:

答案 0 :(得分:0)

查询返回薪水高于 2 其他薪水的所有员工。括号是误导性的,不需要。

select * from employee e 
where 2 = (select count(distinct(e1.sal))
            from employee e1
            where e.sal > e1.sal);

例如,给出以下员工数据:

      Employee  Salary
       Joe     $80,000
       Kate    $80,000
       Lee     $85,000
       Chris   $85,000
       Matt    $85,000
       Mike    $90,000
       June    $90,000
       Jack    $100,000
 The query returns
       Mike    $90,000
       June    $90,000      
  because 90,000 is greater than 80,000 and 85,000

 Notice that Jack is not returned because his salary is greater than 3 other salaries.  Also note there are 5 employees with a salary less than Mike's and June's but the distinct keyword forces the count to 2.

答案 1 :(得分:0)

如上所述,数字2周围的括号无用。等价查询可以是

SELECT * FROM 
(
  select sal, DENSE_RANK() OVER (ORDER BY sal) dr from employee
) emp
WHERE emp.dr = 3

sqlfiddle

正如您在示例中所看到的,您正在搜索员工表中存在两个不同较低工资的员工。