Find max and second max salary for a employee table MySQL

前端 未结 30 1918
忘掉有多难
忘掉有多难 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:42
    $q="select * from info order by salary desc limit 1,0"; // display highest 2 salary
    

    or

    $q="select * from info order by salary desc limit 1,0"; // display 2nd highest salary
    
    0 讨论(0)
  • 2020-12-12 21:42
    select * from
      Employees where Sal >=
      (SELECT
        max(Sal)
    FROM
        Employees
    WHERE
        Sal < (
            SELECT
                max(Sal)
            FROM
                Employees; 
        ));
    
    0 讨论(0)
  • 2020-12-12 21:44
    `select max(salary) as first, (select salary from employee order by salary desc limit 1, 1) as second from employee limit 1`
    

    For max salary simply we can use max function, but second max salary we should use sub query. in sub query we can use where condition to check second max salary or simply we can use limit.

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

    Try

    SELECT 
    
       SUBSTRING( GROUP_CONCAT( Salary ), 1 , LOCATE(",", GROUP_CONCAT( Salary ) ) -1 ) AS max_salary,
    
       SUBSTRING( GROUP_CONCAT( Salary ), LOCATE(",", GROUP_CONCAT( Salary ) ) +1 ) AS second_max_salary
    
    FROM 
       (
         SELECT Salary FROM `Employee` ORDER BY Salary DESC LIMIT 0,2
       ) a
    

    Demo here

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

    You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know a couple of them e.g. in MySQL without using the LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM.

    Generic SQL query:

    SELECT
        MAX(salary)
    FROM
        Employee
    WHERE
        Salary NOT IN (
            SELECT
                Max(Salary)
            FROM
                Employee
        );
    

    Another solution which uses sub query instead of NOT IN clause. It uses < operator.

    SELECT
        MAX(Salary)
    FROM
        Employee
    WHERE
        Salary < (
            SELECT
                Max(Salary)
            FROM
                Employee
        );
    
    0 讨论(0)
  • 2020-12-12 21:45

    This should work same :

    SELECT MAX(salary) max_salary,
      (SELECT MAX(salary)
       FROM Employee
       WHERE salary NOT IN
           (SELECT MAX(salary)
            FROM Employee)) 2nd_max_salary
    FROM Employee
    
    0 讨论(0)
提交回复
热议问题