Sql语句-力扣Leetcode例题之一

1.第二高的薪水

题目:
第二高的薪水
在这里插入图片描述
结题思路:
首先用order by 排序,降序排列加上desc,再用distinct去重,得到薪水唯一值由高到低排列。再用limit num1 offset num2函数选择第二高的薪水。num2代表跳过的个数。
注意:没有第二高时返回null,所以建一个临时表

SELECT
    (SELECT DISTINCT
            Salary
        FROM
            Employee
        ORDER BY Salary DESC
        LIMIT 1 OFFSET 1) AS SecondHighestSalary

2.第N高的薪水

在这里插入图片描述
结题思路:
跟上相同,limit跳过N-1个数即可,但是sql无法识别N-1,所以利用creat函数。
这里利用的是group by之后再order by

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N = N-1;
  RETURN (
      # Write your MySQL query statement below.
      select Salary #as  getNthHighestSalary(2) 
      from Employee 
      group by Salary
      order by Salary desc
      limit 1 offset N
  );
END

3.第N高的薪水

在这里插入图片描述

select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank
from Scores a
order by a.Score DESC

4.分数排名

如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
在这里插入图片描述
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
在这里插入图片描述
解题思路:
1.对分数Score进行排序,利用order by desc
2.对于每一个Score,利用where选择大于等于其的分数,并计数count(唯一值,所以加distinct)
第一步:

select a.Scores 
from Scores as a 
order by a.Scores desc

第二步:加上Rank

select a.Score as Score,
(select count(distinct b.Score) from Scores as b where b.Score >= a.Score) as `Rank`
from Scores a
order by a.Score DESC

5.超过经理收入的员工

Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。
在这里插入图片描述

给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。
在这里插入图片描述

解题思路:
1.涉及Id和ManagerId 需要对表进行两次select,建立表连接
2.可以利用where 或者join进行连接。条件:连接ManagerId=Id ,表1Salary >表2

方法一,利用where:

select a.Name  as  Employee 
from 
Employee as a ,
Employee as b 
where 
a.ManagerId=b.Id
and a.1Salary>b.1Salary

方法二,利用join:

SELECT
a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary

6.查找重复的电子邮箱

编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。
在这里插入图片描述

根据以上输入,你的查询应返回以下结果:
在这里插入图片描述
解题思路:
1.计算每个邮箱出现的频数,利用order by 和count
2.筛选频数大于等于2的邮箱,利用where,需要建立临时表

方法一,先建立临时表:

select Email,count(Email) as Email_e
from Person 
group by Email

方法一,加入where:

select Email
from 
(select Email,count(Email) as Email_e
from Person 
group by Email) as temp
where Email_e>1

方法二,利用having,解决group by和where不能同时应用的问题:

select Email
from Person 
group by Email
having count(Email)>1

7.从不订购的客户

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
在这里插入图片描述
在这里插入图片描述

根据以上输入,你的查询应返回以下结果:
在这里插入图片描述

方法一,利用not in,即Customers表的Id不在Orders表中的CustomerId:

SELECT Name  as Customers 
from Customers 
WHERE Id not in (SELECT CustomerId FROM Orders )

方法二,利用is null,先用left join连接两个函数,然后用wher筛选

select c.Name  as Customers
from Customers as c 
left join  Orders as o
on c.Id=o.CustomerId 
where 
o.Id is null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值