选择员工信息,其中IsManager列引用两个表(任一条件)

时间:2017-06-09 08:21:16

标签: sql sql-server

我有一个Employee表,其中包含EmployeeIdReportsToEmployeeId列,用于定义员工是否以及如何向其他员工报告。

EmployeeId, ReportsToEmployeeId     IsManager
----------------------------------------------
2           1                       1
3           2                       0
4           2                       0
5           2                       0
6           2                       0
7           2                       0
8           2                       0

我还有另一张表AssistantManager。此表包含两列AssistantManagerEmployeeIdReportsToEmployeeId

AssistantManagerEmployeeId, ReportsToEmployeeId
-----------------------------------------------
3                           1
6                           1

我从Employee表中选择了包含列IsManager的员工。如果IsManager表包含1,或者员工在Employee表中,则AssistantManager列必须为1。为了获得该列表,我写下面的查询 -

SELECT
    E.EmployeeId,
    E.ReportsToEmployeeId,
    IsManager = (CASE 
                    WHEN E.IsManager = 1 
                        THEN E.IsManager 
                    ELSE 
                        (CASE 
                            WHEN AM.AssistantManagerEmployeeId IS NULL
                               THEN 0 
                               ELSE 1 
                         END)
                 END)
FROM 
    Employee E
LEFT JOIN 
    AM ON AM.AssistantManagerEmployeeId = E.EmployeeId
WHERE 
    E.EmployeeId = 4 -- This result 4, 2, 0

如果不使用两个案例陈述,请告诉我一个更有效的查询吗?

非常感谢,Thirumalai M

2 个答案:

答案 0 :(得分:1)

试试这个,假设你的sql返回正确的结果..因为我只是在修改case-when-then块:

SELECT
    E.EmployeeId,
    E.ReportsToEmployeeId,
    CASE
    WHEN E.IsManager = 1 OR
         AM.AssistantManagerEmployeeId IS NOT NULL THEN 1
    ELSE 0 
    END AS IsManager 

FROM 
    Employee E
LEFT JOIN 
    AM ON AM.AssistantManagerEmployeeId = E.EmployeeId
WHERE 
    E.EmployeeId = 4

答案 1 :(得分:0)

您可以将这两种情况合二为一: -

IsManager = (CASE 
                WHEN E.IsManager = 1 or AM.AssistantManagerEmployeeId IS NOT NULL
                    THEN 1 
                ELSE 0
            END)