寻找不是经理的员工

时间:2019-03-01 14:28:33

标签: sql sql-server

我有一个表,其中有staff_id和manager_id。随附的屏幕截图。

我通过以下查询找到了经理:

select e.first_name as employee , m.first_name as manager
from sales.staffs E
inner JOIN sales.staffs M ON M.staff_id = E.manager_id

我如何提取非经理员工的名单?

我的样品表

My sample table

4 个答案:

答案 0 :(得分:4)

您可以使用:

select * from sales.staff 
where staff_id not in (select manager_id from sales.staff)

答案 1 :(得分:0)

作为@The Impalers正确答案的扩展,您的查询将变为:

select e.first_name as employee , m.first_name as manager
from sales.staffs E
inner JOIN sales.staffs M ON M.staff_id = E.manager_id
WHERE m.manager_id IS NULL

由于要列出不是经理的人员列表,因此可以使用此解决方案,该解决方案将检查manager_id是否等于NULL(假设这意味着没有经理)。

一个不同的解决方案是基于NOT EXIST的LEFT JOIN,这将过滤您的表并显着减少获取时间。

答案 2 :(得分:0)

我猜所有管理者的ID都存储在manager_id列中。
同样,如果列manager_idnull,则该员工也是经理(?)。
因此,要获得所有经理,您应该做:

select * from sales.staffs 
where 
  manager_id is null
  or
  staff_id in (select distinct manager_id from sales.staffs)

现在要获得不是经理的员工,您只需取消条件:

select * from sales.staffs 
where 
  manager_id is not null
  and
  staff_id not in (select distinct manager_id from sales.staffs)

答案 3 :(得分:0)

不存在

select t1.* from from sales.staff t1
         where not exists ( select 1 from sales.staff t2 where t1.staff_id=t2.manager_id )

如果您使用not in,请执行null chechk

select t.* from sales.staff  t 
where t.staff_id not in (select manager_id from sales.staff where manager_id IS NOT NULL)
相关问题