SQL 181. 超过经理收入的员工 Truncate

题目:

Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

±—±------±-------±----------+
| Id | Name | Salary | ManagerId |
±—±------±-------±----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
±—±------±-------±----------+
给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

±---------+
| Employee |
±---------+
| Joe |
±---------+

Create table If Not Exists Employee (Id int, Name varchar(255), Salary int, ManagerId int);
Truncate table Employee;
insert into Employee (Id, Name, Salary,ManagerId) values ('1', 'Joe', '70000', '3');
insert into Employee (Id, Name, Salary,ManagerId) values ('2', 'Henry', '80000', '4');
insert into Employee (Id, Name, Salary,ManagerId) values ('3', 'Sam', '60000', Null);
insert into Employee (Id, Name, Salary,ManagerId) values ('4', 'Max', '90000', Null);

知识点1:代码理解

Create table If Not Exists Employee (Id int, Name varchar(255), Salary int, ManagerId int);
创建表如果不存在表 表名 (列名 列类型,列名 列类型,……,列名 列类型)
Truncate table Employee;
删除表中的所有行
insert into Employee (Id, Name, Salary,ManagerId) values (‘1’, ‘Joe’, ‘70000’, ‘3’);
插入表名(列名,列名……,列名)values(每一行的数据)

知识点2:Truncate table用于删除表中的所有行,而不记录单个行删除操作

当你不再需要该表时, 用 drop;当你仍要保留该表,但要删除所有记录时, 用 truncate;当你要删除部分记录时(always with a WHERE clause), 用 delete.

答案1

这道题给我们了一个Employee表,里面有员工的薪水信息和其经理的信息,经理也属于员工,其经理Id为空,让我们找出薪水比其经理高的员工,那么就是一个很简单的比较问题了,我们可以生成两个实例对象进行内交通过ManagerId和Id,然后限制条件是一个Salary大于另一个即可:

select name Employee from Employee e1
where e1.Salary > (select e2.Salary from Employee e2 where e1.ManagerId = e2.Id)

答案2

select e1.Name Employee
from Employee e1
left join Employee e2 on e1.ManagerId=e2.Id
where e1.Salary> e2.Salary

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值