查找员工是否是经理

时间:2019-11-02 18:44:32

标签: sql sql-server sql-server-2012

我有2个表employeeemployeeManager

Employee表具有3列:

employeeId (pk), firstname, lastname

EmployeeManager表有5列:

employeemanagerid (PK), 
employeeid (FK references employee > employeeid), 
managerid  (FK references employee > employee id), 
effectivestartdate,
effectiveenddate

我需要将记录显示为

Employeeid, firstname, lastname, isManager

IsManager列可以有2个值:Y表示是,N表示否。

我需要找到今天的状态。即在当天运行查询。

有帮助吗?

2 个答案:

答案 0 :(得分:1)

假设您有一条规则,规定经理中有人向他或她报告。在现实世界中并非如此,但回答您的问题是必要的。

您基本上想要一个exists子句来查看是否存在向经理报告的任何人。看起来像:

select e.*,
       (case when exists (select 1
                          from employeemanager m
                          where m.managerid = e.employeeid and
                                m.effectivestartdate <= getdate() and
                                m.effectiveenddate > getdate()
                         )
             then 'Y' else 'N'
        end) as isManager
from employee e;

答案 1 :(得分:1)

此子查询:

select distinct managerid
from employeemanager
where convert(date, getdate()) between effectivestartdate and effectiveenddate 

返回所有经理。
将表employee左连接到该子查询,并使用CASE表达式获得所需的结果:

select e.*, 
  case when t.managerid is null then 'N' else 'Y' end isManager
from employee e left join (
  select distinct managerid
  from employeemanager
  where convert(date, getdate()) between effectivestartdate and effectiveenddate 
) t on t.managerid = e.employeeid