首页 > 解决方案 > 选择既是经理又在经理手下工作的员工

问题描述

我正在尝试构建一个查询来选择所有员工,他们是经理,但也在经理下工作。

例如在下表中

ID 姓名 manager_id
1 更新鲜 2
2 组长 3
3 经理 空值

我只想获得团队负责人,作为我的选择查询的结果,我尝试使用以下查询,但出现错误。我也不确定这是否是正确的方法。

select e.id, e.name, m.name as mgr_name, 
case when EXISTS (select 1 from emps where emps.manager_id = e.id) then 1
     else 0 end as isMgr
from emps e 
join emps m on e.mgr_id = m.id
where e.manager_id is not null and e.isMgr = 1

错误:

列名“isMgr”无效。

标签: sqlsql-serverjoinself-join

解决方案


我只会使用exists和过滤:

select e.*
from emps e
where e.manager_id is not null and
      exists (select 1
              from e e2
              where e2.manager_id = e.id
             );

推荐阅读