SQL架构:
Create table If Not Exists Employee (Id int, Salary int);
Truncate table Employee;
insert into Employee (Id, Salary) values ('1', '100');
insert into Employee (Id, Salary) values ('2', '200');
insert into Employee (Id, Salary) values ('3', '300');
查看所有记录:
mysql> select * from Employee;
+------+------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+------+------+--------+--------------+
| 1 | NULL | 100 | NULL |
| 2 | NULL | 200 | NULL |
| 3 | NULL | 300 | NULL |
+------+------+--------+--------------+
3 rows in set (0.00 sec)
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary)。
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+-----------------------------+
| SecondHighestSalary |
+-----------------------------+
| 200 |
+-----------------------------+
查询:
方法一:
mysql> select ifnull(salary,NULL) as SecondHighestSalary from
-> (select * from employee order by salary desc)e
-> limit 1 offset 1;
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
1 row in set (0.00 sec)
方法二:
mysql> select ifnull(Salary,NULL) as SecondHighestSalary from
-> Employee e1
-> where (select count(distinct salary) from Employee e2 where e2.salary>e1.salary)=1;
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
1 row in set (0.00 sec)
网友评论