LeetCode176. Second highest and nth highest salary

LeetCode176. Second highest and nth highest salary

Write a SQL query to get the second highest salary in the Employee table (Salary).

Insert picture description here

Solution 1: Use limit to limit this method can be applied to find the Nth highest salary

The usage of imit is: select * from tableName limit i,n
tableName: table name
i: the index value of the query result (starting from 0 by default), when i=0, imit can be omitted
n: the number of returned query results
i and Use English comma "," to separate between n

select
(select distinct Salary 
from Employee 
order by Salary 
desc limit 1,1) 
as SecondHighestSalary

Experience:
1. Pay attention to remove duplicate salary
3. Use ASC or DESC keywords to set the query results to be sorted in ascending or descending order. By default, it is sorted by ASC in ascending order.
2. Pay attention to the usage of limit, the index starts from 0, and the second highest index after descending order is 1

Solution 2: Use the IFNULL() function

The syntax format of the IFNULL() function is: IFNULL(expression, alt_value) The IFNULL
() function is used to determine whether the first expression is NULL, if it is NULL, it returns the value of the second parameter, if it is not NULL, it returns the first The value of each parameter.

select ifnull
(
	(select distinct Salary 
	from Employee 
	order by Salary 
	desc limit 1,1),null) 
as SecondHighestSalary

Experience:
1. Note that ifnull is used in the select query
2. If it is null, return the second parameter, and non-null return the first parameter

Insert picture description here

sql custom function

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    SET N= N-1;
    RETURN (
      # Write your MySQL query statement below.
      select ifnull(
          (select distinct Salary 
          from Employee order by Salary desc 
          limit N,1),
          null)
  );
END

Experience:
1. Pay attention to the setting of N cannot be in return
2. Variable declaration: DECLARE
3. CREATE FUNCTION Foo(N INT) - Passed in an int type parameter N
RETURNS INT - Note that the return is a Data type
BEGIN
DECLARE M INT
SET N = 3
RETURN (a SQL statement)
END

Guess you like

Origin blog.csdn.net/weixin_46801232/article/details/108599263