SQL: Select 来自不同子查询中的多个 JOINS

SQL: Select from multiple JOINS in different subqueries

我有两个 tables EmployeesAssignments,其内容如下图所示(分别输出 A 和 B)。 Employees 中的每个员工最多。 1 名项目负责人 (Assignment.A_Leader = 1) 和最多。 1 个项目控制器 (Assignment.A_Controller = 1) 分配。我想获得所有员工的列表,以及他们领导或控制的项目。如果员工没有此类分配,则应显示 NULL。我设法列出领导或项目分配。但是,我没能按照 here 的建议(参见尝试 E)将两者放在正确的列表中。我必须添加什么才能获得所需的最终结果 table?

下面代码的字母 A-E 对应于图像中输出的字母 A-E。

我正在使用 Microsoft SQL Server 2017。

-- A: all employees
SELECT * FROM Employee

-- B: all assignments
SELECT * FROM Assignment

-- C: employees with their projects as LEADERS
SELECT E.E_FirstName as First, E.E_LastName as Last, L.A_ProjectID as Leader
FROM Employee E LEFT JOIN
(SELECT A.E_ID, A_ProjectID FROM Assignment A WHERE A.A_Leader=1) L
ON E.E_ID = L.E_ID

-- D: employees with their projects as CONTROLLERS
SELECT E.E_FirstName as First, E.E_LastName as Last, C.A_ProjectID as Controller
FROM Employee E LEFT JOIN
(SELECT A.E_ID, A_ProjectID FROM Assignment A WHERE A.A_Controller=1) C
ON E.E_ID = C.E_ID

-- E: employees with their projects as LEADERS or CONTROLLERS
SELECT X.First, X.Last, X.Leader, Y.Controller FROM
(SELECT E.E_FirstName as First, E.E_LastName as Last, L.A_ProjectID as Leader
FROM Employee E LEFT JOIN
(SELECT A.E_ID, A_ProjectID FROM Assignment A WHERE A.A_Leader=1) L
ON E.E_ID = L.E_ID) as X,
(SELECT E.E_FirstName as First, E.E_LastName as Last, C.A_ProjectID as Controller
FROM Employee E LEFT JOIN
(SELECT A.E_ID, A_ProjectID FROM Assignment A WHERE A.A_Controller=1) C
ON E.E_ID = C.E_ID) as Y

您可以 left join assignments table 两次:

select
    e.e_first_name,
    e.e_last_name,
    al.a_project_id leader,
    ac.a_project_id controller
from employee e
left join assignments al on al.e_id = e.e_id and al.a_leader     = 1
left join assignments ac on ac.e_id = e.e_id and ac.a_controller = 1