赞
踩
题目:
第二高的薪水
结题思路:
首先用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
结题思路:
跟上相同,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
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
如果两个分数相同,则两个分数排名(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
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
编写一个 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
某网站包含两个表,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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。