LeetCode sql语句 学习专题【Medium】

题目链接如下: https://leetcode.com/problemset/database/


目录

626. Exchange Seats

178. Rank Scores

180. Consecutive Numbers

184. Department Highest Salary

177. Nth Highest Salary


626. Exchange Seats

交换相邻两个记录的某个字段,使用CASE WHEN,使用select count(*) from 统计有多少字段

# Write your MySQL query statement below
select (
    CASE
        WHEN MOD(id,2)=1 and id!=counts THEN id+1
        WHEN MOD(id,2)=0 THEN id-1
        ELSE id
    END
)as id,student from
(
    select count(*) as counts from seat    
)A,seat
order by id ASC;

178. Rank Scores

统计分数排名,先选出不同的分数,根据大小关系确定排名

# Write your MySQL query statement below
select Score,(
    select count(*) from ( select distinct Score as s from Scores)t where s>=Score
)Rank 
from Scores order by Score DESC

 


180. Consecutive Numbers

问记录里连续出现至少3次的数字是什么。左连接两次,并注意distinct

# Write your MySQL query statement below

select distinct res.aNum as  ConsecutiveNums from (
select tmp.Id,aNum,bNum,c.Num as cNum from
(
    select a.Id,a.Num as aNum,b.Num as bNum from Logs as a 
    left join Logs b on a.Id+1 = b.Id
    )tmp left join Logs c on c.Id = tmp.Id+2
)res 
where res.aNum = res.bNum and res.bNum = res.cNum

#标准解法
SELECT DISTINCT
    l1.Num AS ConsecutiveNums
FROM
    Logs l1,
    Logs l2,
    Logs l3
WHERE
    l1.Id = l2.Id - 1
    AND l2.Id = l3.Id - 1
    AND l1.Num = l2.Num
    AND l2.Num = l3.Num
;

 

184. Department Highest Salary

找到各个部门里的最高工资,先选出各个部门的最高工资,判断对应DepartmentId和Salary是都存在其中

# Write your MySQL query statement below
select tmp.DepartmentName as Department ,tmp.name as Employee,Salary from (
    select a.Id,a.Name,a.Salary,a.DepartmentId,b.Name as DepartmentName from Employee a  join Department b on a.DepartmentId = b.Id
)tmp 
where (tmp.DepartmentId , Salary) in
(
    select DepartmentId,max(salary) from Employee group by DepartmentId
)

SELECT
    Department.name AS 'Department',
    Employee.name AS 'Employee',
    Salary
FROM
    Employee
        JOIN
    Department ON Employee.DepartmentId = Department.Id
WHERE
    (Employee.DepartmentId , Salary) IN
    (   SELECT
            DepartmentId, MAX(Salary)
        FROM
            Employee
        GROUP BY DepartmentId
    )
;

不使用 left join的原因是,左连接出null 字段,左边没有的内容会出现null


177. Nth Highest Salary

找到第N大的工资,需要用到函数

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N=N-1;
  RETURN (
      # Write your MySQL query statement below.
      select DISTINCT Salary from
        Employee order by Salary DESC limit N,1
      
  );
END

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值