1 第二高的薪水
我的代码:
SELECT Salary SecondHighestSalary
FROM Employee
ORDER BY Salary DESC
LIMIT 1, 1
我的代码不满足示例2的情况:如果没有第 2 高的薪资,即表里可能只有一条记录,这个解答会被评测为 'Wrong Answer' 。为了克服这个问题,我们可以将其作为临时表。
官方代码1:
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
方法2:使用 IFNULL
和 LIMIT
子句
SELECT ifnull((select Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1, 1),null)SecondHighestSalary
2 第 N 高的薪水
官方正确代码:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M = N-1;
RETURN (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT M, 1
);
END
复盘:别问 ,问就是不会,第一次涉及到变量问题。答案中是定义了一个函数getNthHighestSalary
,它接受一个整数参数N,并返回第N高的薪资值。
3 分数排名
我的代码:不知道这个版本能不能用排序窗口函数
select score,dense_rank().over(partition by id order by score desc) as rank
from Scores
细节错误改正:不用安装id分别,表中没有重复,而且题意没有要求
# Write your MySQL query statement below
select score,dense_rank()over( order by score desc) as 'rank'
from Scores
复盘:
● 【排序窗口函数】
● rank()over()——1,1,3,4
● dense_rank()over()——1,1,2,3
● row_number()over()——1,2,3,4
● 【排序窗口函数语法】
● rank()over([partition by 字段名] order by 字段名 asc|desc)
● dense_rank()over([partition by 字段名] order by 字段名 asc|desc)
● row_number()over([partition by 字段名] order by 字段名 asc|desc)
4 连续出现的数字
我的代码
select num ConsecutiveNums
from Logs
group by num
having count(id) > 3
复盘: 聚合函数group后面就不能用where限制条件了,要用having!!!!
(爆卡!!!!!!费劲,不知道是非会员的原因还是我的电脑问题,很卡顿)
5超过经理收入的员工
正确代码1:连续调用同一个表的思想
select a.name 'Employee'
from Employee a,Employee b
where a.managerId = b.id and a.salary>b.salary
正确代码2:join自连接,组合成一个大表
SELECT
a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary
;
复盘:from后面可以逗号连接多个表
6. 查找重复的电子邮箱
我的代码: group by + having , 重复,就是出现次数大于1
select email as Email
from Person
group by email
having count(email)>1
方法2:group by+子查询(临时表)
select Email from
(
select Email, count(Email) as num
from Person
group by Email
) as statistic
where num > 1