Find max and second max salary for a employee table MySQL

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

    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
        );
    

提交回复
热议问题