编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
limit 1,1 从0下标开始,跳过1条数据的一条数据
使用临时表 原因 :select如果查不到会默认返回空
这种方式和IFNULL(exp1,exp2)函数方法一样 :
假如exp1 不为 NULL,IFNULL() 的返回值为 exp1; 否则其返回值为 exp2。IFNULL()的返回值是数字或是字符串,具体情况取决于其所使用的语境
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1,1) AS SecondHighestSalary```
185. 部门工资前三高的所有员工
Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 85000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
| 7 | Will | 70000 | 1 |
+----+-------+--------+--------------+
Department 表包含公司所有部门的信息。
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 85000 |
| IT | Will | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+
解释:
IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。
代码:
第一种写法
select de.name Department ,sa.name Employee,sa.Salary from Employee sa
join Department de on sa.DepartmentId = de.Id
where (
select count(distinct sy.Salary) from Employee sy
where sa.Salary < sy.Salary and sy.DepartmentId = sa.DepartmentId
) < 3
第二种写法 使用窗口函数
select
de.name as Department,
rank1.Name as Employee,
rank1.Salary as Salary
from (select DepartmentId,Name,Salary,DENSE_RANK() over(partition BY DepartmentId order by Salary desc) as ranknum
from Employee) as rank1
join Department de on rank1.DepartmentId = de.Id
where rank1.ranknum <= 3