SQL刷题笔记day6——转战LeetCode

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高的薪资值。

分数排名

我的代码:不知道这个版本能不能用排序窗口函数

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)

连续出现的数字

我的代码

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

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值