SQL query to find Nth highest salary from a salary table

前端 未结 11 2173
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 10:45

How can I find the Nth highest salary in a table containing salaries in SQL Server?

相关标签:
11条回答
  • 2020-11-28 10:57
    SELECT * FROM 
    (select distinct postalcode  from Customers order by postalcode DESC)
    limit 4,1;
    

    4 here means leave first 4 and show the next 1.

    Try this it works for me.

    0 讨论(0)
  • 2020-11-28 11:03

    Dont forget to use the distinct keyword:-

    SELECT TOP 1 Salary
    FROM 
    (
        SELECT Distinct TOP N Salary
        FROM Salaries
        ORDER BY Salary DESC
    ) SalarySubquery
    ORDER BY Salary ASC
    
    0 讨论(0)
  • 2020-11-28 11:06
    EmpID   Name    Salary
    1   A   100
    2   B   800
    3   C   300
    4   D   400
    5   E   500
    6   F   200
    7   G   600
    
    SELECT * FROM Employee E1
    WHERE (N-1) = (
                    SELECT COUNT(DISTINCT(E2.Salary))
                    FROM Employee E2
                    WHERE E2.Salary > E1.Salary
                  )
    

    Suppose you want to find 5th highest salary, which means there are total 4 employees who have salary greater than 5th highest employee. So for each row from the outer query check the total number of salaries which are greater than current salary. Outer query will work for 100 first and check for number of salaries greater than 100. It will be 6, do not match (5-1) = 6 where clause of outerquery. Then for 800, and check for number of salaries greater than 800, 4=0 false then work for 300 and finally there are totally 4 records in the table which are greater than 300. Therefore 4=4 will meet the where clause and will return 3 C 300.

    0 讨论(0)
  • 2020-11-28 11:08

    Very simple one query to find nth highest salary

    SELECT DISTINCT(Sal) FROM emp ORDER BY Salary DESC LIMIT n,1
    
    0 讨论(0)
  • 2020-11-28 11:11

    try it...

    use table_name
    select MAX(salary)
    from emp_salary
    WHERE marks NOT IN (select MAX(marks)
    from student_marks )
    
    0 讨论(0)
  • 2020-11-28 11:12

    The easiest method is to get 2nd higest salary from table in SQL:

    sql> select max(sal) from emp where sal not in (select max(sal) from emp);
    
    0 讨论(0)
提交回复
热议问题