Find max and second max salary for a employee table MySQL

前端 未结 30 1917
忘掉有多难
忘掉有多难 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:45

    Max Salary:

    select max(salary) from tbl_employee <br><br>
    

    Second Max Salary:

    select max(salary) from tbl_employee where salary < ( select max(salary) from tbl_employee);
    
    0 讨论(0)
  • 2020-12-12 21:46

    The Best & Easiest solution:-

     SELECT
        max(salary)
    FROM
        salary
    WHERE
        salary < (
            SELECT
                max(salary)
            FROM
                salary
        );
    
    0 讨论(0)
  • 2020-12-12 21:46

    If we want to find Employee that gets 3nd highest salary then execute this query

    SELECT a.employeeid, 
           a.salary 
    FROM  (SELECT employeeid, 
                  salary, 
                  Dense_rank() 
                    OVER( 
                      ORDER BY salary) AS n 
           FROM   employee) AS a 
    WHERE  n = 3 
    

    What do you want

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

    This solution will give all employee name and salary who have second highest salary

    SELECT name, salary
    FROM employee
    WHERE salary = (
        SELECT 
            salary
        FROM employee AS emp
        ORDER BY salary DESC
        LIMIT 1,1
    );
    
    0 讨论(0)
  • 2020-12-12 21:49

    without nested query

    select max(e.salary) as max_salary, max(e1.salary) as 2nd_max_salary 
    from employee as e
    left join employee as e1 on e.salary != e1.salary
    group by e.salary desc limit 1;
    
    0 讨论(0)
  • 2020-12-12 21:50

    try this

    select max(salary) as first, 
           (select salary from employee order by salary desc limit 1, 1) as second 
    from employee limit 1
    
    0 讨论(0)
提交回复
热议问题