数据库练习
3.超过经理收入的员工
链接:https://leetcode-cn.com/problems/employees-earning-more-than-their-managers/
Employee
表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id(ManagerId)。
给定 Employee
表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。
--方法一
--join 是一个更常用也更有效的将表连起来的办法,我们使用on来指明条件。
select
a.Name as Employee
from Employee a join Employee b
on a.ManagerId = b.Id
and a.Salary > b.Salary
;
--方法二:使用where语句
--从两个表里使用 Select 语句可能会导致产生笛卡尔积.在这种情况下我们使用where来进行筛选
select a.Name as 'Employee' from Employee a,Employee b
where a.ManagerId=b.Id
and a.Salary>b.Salary;
4.查找重复的电子邮箱
链接:https://leetcode-cn.com/problems/duplicate-emails/
编写一个 SQL 查询,查找 Person
表中所有重复的电子邮箱。
--重复的电子邮箱存在多次。要计算每封电子邮件的存在次数,我们可以使用以下代码
select Email, count(Email) as num
from Person
group by Email;
--针对临时表我们可以进一步进行解题
select Email from
(
select Email, count(Email) as num
from Person
group by Email
) as statistic
where num > 1
;
解析:SELECT 中使用 GROUP BY 子句可以对指定列进行分组查询。需要满足:使用 GROUP BY 进行分组查询时,SELECT 指定的字段必须是“分组依据字段”,其他字段若想出现在SELECT 中则必须包含在聚合函数中。
同时我们可以引进having
--引进having
select Email
from Person
group by Email
having count(Email)>1;