How to find third or nᵗʰ maximum salary from salary table?

后端 未结 30 562
醉酒成梦
醉酒成梦 2020-11-30 16:30

How to find third or nth maximum salary from salary table(EmpID, EmpName, EmpSalary) in optimized way?

相关标签:
30条回答
  • 2020-11-30 17:06

    If you want optimize way means use TOP Keyword, So the nth max and min salaries query as follows but the queries look like a tricky as in reverse order by using aggregate function names:

    N maximum salary:

    SELECT MIN(EmpSalary)
    FROM Salary
    WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary DESC) 
    

    for Ex: 3 maximum salary:

    SELECT MIN(EmpSalary)
    FROM Salary
    WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary DESC) 
    

    N minimum salary:

    SELECT MAX(EmpSalary)
    FROM Salary
    WHERE EmpSalary IN(SELECT TOP N EmpSalary FROM Salary ORDER BY EmpSalary ASC)
    

    for Ex: 3 minimum salary:

    SELECT MAX(EmpSalary)
    FROM Salary
    WHERE EmpSalary IN(SELECT TOP 3 EmpSalary FROM Salary ORDER BY EmpSalary ASC)
    
    0 讨论(0)
  • 2020-11-30 17:07

    Method 1:

    SELECT TOP 1 salary FROM (
    SELECT TOP 3 salary 
     FROM employees 
      ORDER BY salary DESC) AS emp 
     ORDER BY salary ASC
    

    Method 2:

      Select EmpName,salary from
      (
        select EmpName,salary ,Row_Number() over(order by salary desc) as rowid      
         from EmpTbl)
       as a where rowid=3
    
    0 讨论(0)
  • 2020-11-30 17:07
    set @n = $n
    
    SELECT a.* FROM ( select a.* , @rn = @rn+1  from EMPLOYEE order by a.EmpSalary desc ) As a  where rn = @n
    
    0 讨论(0)
  • 2020-11-30 17:07

    To query the nth highest bonus, say n=10, using AdventureWorks2012, Try Following code

    USE AdventureWorks2012; 
    GO
    
    SELECT * FROM Sales.SalesPerson;
    GO
    
    DECLARE @grade INT;
    SET @grade = 10;
    SELECT MIN(Bonus)
    FROM (SELECT TOP (@grade) Bonus FROM (SELECT DISTINCT(Bonus) FROM Sales.SalesPerson) AS a ORDER BY Bonus DESC) AS g
    
    0 讨论(0)
  • 2020-11-30 17:08

    Try this Query

    SELECT DISTINCT salary
    FROM emp E WHERE
    &no =(SELECT COUNT(DISTINCT salary) 
    FROM emp WHERE E.salary <= salary)
    

    Put n= which value you want

    0 讨论(0)
  • 2020-11-30 17:09

    Try this code :-

    SELECT *
       FROM one one1
       WHERE ( n ) = ( SELECT COUNT( one2.salary )
                       FROM one one2
                       WHERE one2.salary >= one1.salary
                     )
    
    0 讨论(0)
提交回复
热议问题