Find max and second max salary for a employee table MySQL

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

    with Common table expression

    With cte as (
     SELECT 
       ROW_NUMBER() Over (Order By Salary Desc) RowNumber, 
       Max(Salary) Salary 
     FROM
         Employee
     Group By Salary
    )
    
    Select * from cte where RowNumber = 2
    
    0 讨论(0)
  • 2020-12-12 21:33

    You can just run 2 queries as inner queries to return 2 columns:

    select
      (SELECT MAX(Salary) FROM Employee) maxsalary,
      (SELECT MAX(Salary) FROM Employee
      WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as [2nd_max_salary]
    

    SQL Fiddle Demo

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

    Not really a nice query but :

    SELECT * from (
        SELECT max(Salary) from Employee
        ) as a
    LEFT OUTER JOIN 
        (SELECT MAX(Salary) FROM Employee
            WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )) as b
    ON 1=1
    
    0 讨论(0)
  • 2020-12-12 21:33
    select * from emp where sal =(select max(sal) from emp where eno in(select eno from emp where sal <(select max(sal)from emp )));
    

    try the above code ....

    if you want the third max record then add another nested query "select max(sal)from emp" inside the bracket of the last query and give less than operator in front of it.

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

    Here change n value according your requirement:

    SELECT top 1 amount 
    FROM ( 
        SELECT DISTINCT top n amount 
        FROM payment 
        ORDER BY amount DESC ) AS temp 
    ORDER BY amount
    
    0 讨论(0)
  • 2020-12-12 21:37

    Try like this

    SELECT (select max(Salary) from Employee) as MAXinmum),(max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary)) FROM Employee);
    

    (Or)

    Try this, n would be the nth item you would want to return

     SELECT DISTINCT(Salary) FROM table ORDER BY Salary DESC LIMIT n,1
    

    In your case

     SELECT DISTINCT(column_name) FROM table_name ORDER BY column_name DESC limit 2,1;
    
    0 讨论(0)
提交回复
热议问题