当前位置:网站首页>Database query - what is the highest data?

Database query - what is the highest data?

2022-07-07 23:57:00 Liu Chu, Ge Nian

Data sheet

Employee  surface :
+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id  It's the primary key of this table .
 Each row of the table contains the salary information of the employee .

subject 2: The second highest salary

Write a SQL Inquire about , Get and return Employee The second highest salary on the list . If there is no second highest salary , The query should return null .

The query result is shown in the following example .

 Example  1:

 Input :
Employee  surface :
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
 Output :
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+
 Example  2:

 Input :
Employee  surface :
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
 Output :
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                |
+---------------------+

answer

select ifNull(
(select distinct salary
from Employee 
order by Salary Desc
limit 1,1),null
) as SecondHighestSalary;

Look at this :https://leetcode.cn/problems/second-highest-salary/solution/tu-jie-sqlmian-shi-ti-ru-he-cha-zhao-di-ngao-de-sh/

subject 3: The first N High salary

Write a SQL Query to report Employee No n High wages . If there is no n A maximum wage , The query should be reported as null .

 The query result format is as follows .

 Example  1:

 Input : 
Employee table:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
n = 2
 Output : 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+
 Example  2:

 Input : 
Employee  surface :
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
n = 2
 Output : 
+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| null                   |
+------------------------+

answer

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare m int;
SET m = N-1;
  RETURN (
      # Write your MySQL query statement below.
      select ifNull(
          (
              select distinct salary 
              from Employee 
              order by salary desc 
              limit 1 offset m
          ),null) 
  );
END
原网站

版权声明
本文为[Liu Chu, Ge Nian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072148475957.html