leetcode MYSQL数据库题目176

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_30650153/article/details/81806635

176. second highest salary

1、题目与答案

Table: Employee

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

Write a SQL query to get the second highest salary from the Employee table.
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

Table:SecondHighestSalary

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

编写SQL语句从Employee表中获得第二高的薪水。
例如,给定上面的Employee表,查询应返回200作为第二高薪。如果没有第二高工资,则查询应返回null

答案是:
select IFNULL(
(select distinct Salary from Employee order by Salary desc
limit 1, 1),
NULL
) as SecondHighestSalary;


2、知识点总结

验证答案步骤
1、创建表employee

create table employee(
id int NULL,
Salary int NULL
);

2、插入数据

insert into employee
values(1,100),(2,200),(3,300);

3、运行答案得到:

+---------------------+
| SecondHighestSalary |
+---------------------+
|                 200 |
+---------------------+
1 row in set (0.10 sec)

这只是终端打印出来,若想生成该表,应执行:
create table secondhighestsalary
select IFNULL(
(select distinct Salary from Employee order by Salary desc
limit 1, 1),
NULL
) as SecondHighestSalary;

知识点:

  • IFNULL(expr1,expr2) 如果expr1不是 NULLIFNULL() 返回 expr1,否则它返回expr2
  • select ... as sth; 这个指的是生成一个列名
  • 在需要返回记录不同的id的具体值的时候可以用,比如select distinct id from tablename;返回talbebname表中不同的id的具体的值。
  • order by ... desc 降序排列
  • limit 1,1 检索记录行第2行开始的1个

猜你喜欢

转载自blog.csdn.net/qq_30650153/article/details/81806635