leetcode sql 刷题记录

176.查找第二高的薪水纪录
Write a SQL query to get the second highest salary from the Employee table.
±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+

输出例子
±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+

select ifnull
((select salary  from employee
group by salary
order by salary desc
limit 1 offset 1),null)
as SecondHighestSalary

ifnull(,null)如果逗号前面是null就输出null,题目要求第二高为空输出null而不是空

177.提交第n高的薪水

CREATE FUNCTION getNthHighestSalary(N INT) 
RETURNS INT
BEGIN    
  set N=N-1;  
  IF N < 0 
  THEN  RETURN NULL;  
  else  RETURN (      
  # Write your MySQL query statement below.     
  select ifnull( (select distinct salary       
  from employee order by salary desc       
  limit N,1),null)  );  
  end if;
  END

难点就在于不能limit n-1,1,要提前set n=n-1,主义严谨的地方n是从0开始的,所以有if n<0,最后也不能忘了end if。然后记得每一个完整的语句后面加分号

178.排名
mysql8.0以上直接用窗口函数,非常方便
窗口函数参考.

select score,
dense_rank() over (order by score desc) as rank
from Scores s 

LeetCode不支持8.0以上版本,考虑复表,也就是自己写rank()

select s1.score,count(distinct s2.score) as 'rank'
from scores s1,scores s2
where  s1.score<=s2.score
group by s1.id
order by score desc 

一定要按照s1.id 分类,才能数出比我大的有几个,不知道为什么leetcode里按照rank order by输不出

今天好累,明天继续2020-05-03

180.输出至少连续出现三次以上的数字
Write a SQL query to find all numbers that appear at least three times consecutively.
±—±----+
| Id | Num |
±—±----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
±—±----+

前面要加distinct,因为可能会有多条记录,但是是同一数字

select  distinct l1.num from 
Logs l1,logs l2,logs l3
where l1.id+1=l2.id and l2.id+1=l3.id
and l1.num=l2.num and l2.num=l3.num

181.收入超过经理的员工
The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
±—±------±-------±----------+
| Id | Name | Salary | ManagerId |
±—±------±-------±----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
±—±------±-------±----------+

select e1.name as 'Employee'
 from employee e1,employee e2
 where e1.salary>e2.salary
 and e2.id=e1.managerid

183.从不订购的用户
在这里插入图片描述
方法一:not in

select  c.name 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值