2.SQL

一.第二高薪水

要点:去重,null


14833822-d9a65a31a54238cb.png
第二高薪水
#解法一:循环查询
SELECT
    (SELECT DISTINCT
            Salary
        FROM
            Employee
        ORDER BY Salary DESC
        LIMIT 1 OFFSET 1) AS SecondHighestSalary
#解法二:ifnull判断
SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

二、第N高薪水

要点:参数


14833822-b555aa430f1753fd.png
第N高薪水
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
        set n = n-1;
  RETURN (
      select ifnull(
          (select distinct Salary from Employee
           order by salary desc
           limit n , 1
              
        )
        ,null) as getNthHighestSalary
      
  );
END

三、分数排名

要点:变量,嵌套循环


14833822-fb83c5d36a1df7d7.png
分数排名
利用@a变量的作为基数,@pre判断分数是否发生改变(改变为1,未变为0),循环得到Rank
select Score,@a := @a+(@pre<>(@pre := Score)) as Rank from Scores,
(select @a := 0,@pre := 0)t
order by Score desc
将大小比较结果作为子查询返回为Rank,注意对子查询的Score去重。
select a.Score,
(select  count(distinct b.score) from Scores as b where (a.score<=b.score)) as Rank
from Scores as a
order by Score desc

四、连续出现的数字

要点:自连接,将本身一张表复制为多张相同的表来使用。


14833822-b9b9255ab2eefdb0.png
连续数字
select DISTINCT L1.NUM AS ConsecutiveNums from 
logs as L1,
logs as L2,
logs as L3
where
L1.ID = L2.ID-1
AND
L2.ID = L3.ID-1
AND
L1.NUM=L2.NUM
AND
L2.NUM=L3.NUM

五、超过经理收入的员工

要点:自连接,内连接


14833822-d65a83cae11b5fd8.png
超过经理收入的员工
select L1.name as Employee 
from 
Employee as L1,
Employee as L2
where
L1.ManagerId=L2.Id
and
L1.Salary>L2.Salary
SELECT a.NAME AS Employee
FROM 
Employee AS a 
JOIN Employee AS b
ON a.ManagerId = b.Id
AND 
a.Salary > b.Salary
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值