Find max and second max salary for a employee table MySQL

前端 未结 30 1919
忘掉有多难
忘掉有多难 2020-12-12 21:19

Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:

  Employee
  Employee ID    S         


        
相关标签:
30条回答
  • 2020-12-12 21:51

    I think, It is the simplest way to find MAX and second MAX Salary.You may try this way.

    SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.
    
    SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary
    
    0 讨论(0)
  • 2020-12-12 21:52

    For unique salaries (i.e. first can't be same as second):

    SELECT
      MAX( s.salary ) AS max_salary,
      (SELECT
         MAX( salary ) 
       FROM salaries
       WHERE salary <> MAX( s.salary ) 
       ORDER BY salary DESC 
       LIMIT 1
      ) AS 2nd_max_salary
    FROM salaries s
    

    And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)

    0 讨论(0)
  • 2020-12-12 21:55

    You can write 2 subqueries like this example

    SELECT (select max(Salary) from Employee) as max_id, 
         (select Salary from Employee order by Salary desc limit 1,1) as max_2nd 
    
    0 讨论(0)
  • 2020-12-12 21:55

    Here is another solution which uses sub query but instead of IN clause it uses < operator

    SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);
    
    0 讨论(0)
  • 2020-12-12 21:57

    This is awesome Query to find the nth Maximum: For example: -

    1. You want to find salary 8th row Salary, Just Changed the indexed value to 8.

    2. Suppose you have 100 rows with Salary. Now you want to find Max salary for 90th row. Just changed the Indexed Value to 90.

      set @n:=0;
      select * from (select *, (@n:=@n+1) as indexed from employee order by Salary desc)t where t.indexed = 1;
      
    0 讨论(0)
  • For second highest salary, This one work for me:

    SELECT salary
    FROM employee
    WHERE salary 
    NOT IN (
    SELECT MAX( salary ) 
    FROM employee
    ORDER BY salary DESC
    )
    LIMIT 1
    
    0 讨论(0)
提交回复
热议问题