N(th)最高工资查询

时间:2014-01-02 08:02:15

标签: mysql sql sql-server

我找到了一个从网上找到第n个最高工资的解决方案:

SELECT * FROM Employee Emp1
WHERE (N-1) = (
           SELECT COUNT(DISTINCT(Emp2.Salary))
           FROM Employee Emp2
           WHERE Emp2.Salary > Emp1.Salary
           )

但我无法理解查询是如何实际执行的,即查询在每个步骤中的处理方式,尤其是在同一个表的多个别名出现的子查询中 - >

WHERE Emp2.Salary > Emp1.Salary

比较运算符对此做了什么 -

WHERE (N-1) = <subquery>

有人可以帮我解决一下吗?

2 个答案:

答案 0 :(得分:4)

第N个最高工资是N-1工资较高的工资 例如。最高薪水没有更高的薪水

对查询进行以下更改应演示其工作原理:

SELECT * FROM Employee Emp1
CROSS APPLY
           (
           SELECT COUNT(DISTINCT(Emp2.Salary)) AS NHigher
           FROM Employee Emp2
           WHERE Emp2.Salary > Emp1.Salary
           ) X;

小提琴Sql Server here

但请注意,大多数RDBMS都允许OFFSETLIMIT类型限制,这样您就可以使用普通ORDER BY更有效地检索第N行。

e.g。在SQL Server 2012中,要获取第二高的薪水:

SELECT *
FROM Employee Emp1
ORDER BY SALARY DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;

答案 1 :(得分:0)

编辑:这个问题是问如何获得最高工资或获得最高工资?  这些例子说如何获得n(th)工资获得前n(th)只改变第2行  WHERE emp.Salary =WHERE emp.Salary >=:D

有一个解决方案:

  1. 拿Nth最高薪

  2. 让有薪水的员工

  3. 现在你可以通过以下方式实现它:

    第一个解决方案分组工资:

    SELECT * FROM Employee as emp
    WHERE emp.Salary = 
    (
        SELECT TOP 1 t.Salary FROM 
        (
            SELECT TOP N(th) e.Salary FROM Employee as e
            Group by e.Salary
            Order By e.Salary
        ) as t
        ORDER BY t.Salary DESC
    )
    

    第二个解决方案DISTINCT salarys:

    SELECT * FROM Employee as emp
    WHERE emp.Salary = 
    (
        SELECT TOP 1 t.Salary FROM 
        (
            SELECT DISTINCT TOP N(th) e.Salary FROM Employee as e
            Order By e.Salary
        ) as t
        ORDER BY t.Salary DESC
    )