【问题标题】:Explain how to find the 3rd MAX salary in the emp table解释如何在 emp 表中找到第三个 MAX 工资
【发布时间】:2017-05-05 16:30:51
【问题描述】:

请任何人解释一下以下查询的运行时执行:-

select distinct sal 
from emp e1 
where 3 = (select count(distinct sal) 
           from emp e2 
           where e1.sal <= e2.sal);

【问题讨论】:

  • 更好地解释你的问题.. ?
  • 这是一种非常古老(且效率低下)的计算方法。看看DENSE_RANK吧。

标签: sql oracle


【解决方案1】:
select distinct sal
from emp e1
where 3 = (
        select count(distinct sal)
        from emp e2
        where e1.sal <= e2.sal
        )

这是一个相关查询,这意味着子查询针对外部查询的每一行运行:

子查询返回大于或等于给定薪水的不同薪水的计数

例如emp表中有以下值:

10
20
30
40

假设外部查询位于 sal = 40 的行。子查询返回的计数将为 1。

for sal = 30, count = 2
for sal = 20, count = 3
for sal = 10, count = 4

所以只有符合您条件的行是 sal = 20 的行,这就是您想要的。

更好的方法是使用排名:

select distinct sal
from (
    select t.*,
        dense_rank() over (
            order by salary desc
            ) as rnk
    from your_table t
    ) t
where rnk = 3;

【讨论】:

    【解决方案2】:

    我认为更短的方法是使用(相当新的)功能NTH_VALUE

    SELECT DISTINCT NTH_VALUE(salary, 3) OVER ()
    FROM your_table;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 2012-07-31
      相关资源
      最近更新 更多