【问题标题】:Need explanation regarding the working of a self-join query on same column [duplicate]需要解释在同一列上进行自联接查询的工作[重复]
【发布时间】:2019-05-20 15:39:42
【问题描述】:

问题是使用自连接找到emp表的第二高薪水。

代码如下:

SELECT DISTINCT sal FROM emp e1 
WHERE 2 = (SELECT count(DISTINCT sal) FROM emp e2 WHERE e1.sal <= e2.sal);

有人可以解释一下这个查询背后的工作机制吗?

【问题讨论】:

    标签: sql oracle oracle11g top-n


    【解决方案1】:

    您可以考虑以下带有相关子查询的查询来澄清您的问题

    select ( select max(distinct e2.sal) from emp e2 where e1.sal <= e2.sal ) as max_salary,
           ( select min(distinct e2.sal) from emp e2 where e1.sal <= e2.sal ) as min_salary,
           ( select count(distinct sal)  from emp e2 where e1.sal <= e2.sal ) 
         as salaries_count
      from emp e1
     order by salaries_count;
    
    MAX_SALARY  MIN_SALARY  SALARIES_COUNT
    5000        5000        1
    5000        3000        2
    5000        3000        2
    5000        2975        3
    5000        2850        4
    5000        2450        5
    5000        1600        6
    5000        1500        7
    5000        1300        8
    5000        1250        9
    5000        1250        9
    5000        1100       10
    5000         950       11
    5000         800       12
    

    不同的薪水数量(reversely_exceeding_salaries"低于最高薪水的不同薪水数量 -> 5000")剩余低于最高薪水加薪作为薪水减少

    ( select count(distinct sal) from emp e2 where e1.sal &lt;= e2.sal ) 子查询有两个salary_count,计数值为2,它给出了第二高的薪水。

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 2016-02-03
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      相关资源
      最近更新 更多