条件:城市是'纽约'。如果Manager为NULL,则显示“CEO”。 我已经分享了表结构的链接。
我知道我可以通过子查询,CTE或自我加入来实现这一点。但我是CTE / Self Joins的新手,所以需要一些帮助。
尝试类似下面的内容:但我很困惑如何做到这一点。
WITH CTE EmployeeManager(
Select Concat(FirstName, ,LastName) as [Employee Name]
FROM Contact C JOIN Employee E ON C.ContactID=E.ContactID
Where E.ManagerID IS NULL
UNION ALL
Select Concat(FirstName, ,LastName) as [Employee Name]
FROM Contact C JOIN Employee E ON C.ContactID=E.ContactID
JOIN EmployeeManager EM ON E.ManagerID=EM.EmployeeID
)
Select [Employee Name] from EmployeeManager;
无法继续进行。请帮忙......
答案 0 :(得分:1)
我认为以下内容应该有效或指向正确的方向。我已经假设了一些关于你数据的事情:
1)通过查看Employee表中的EmployeeID和ManagerID来找到经理
2)历史上的员工可能在多个部门工作,而您只是在寻找当前员工,因此EmployeeDepartmentHistory中的EndDate为空
3)员工可能存储了多个地址,因此我使用子查询
选择最新的地址SELECT
Concat(C.FirstName,' ',C.LastName) as [Employee Name],
D.[Department Name],
COALESCE(Concat(M.FirstName,' ',M.LastName),'CEO') as [Manager Name],
A.City,
SP.StateProvinceCode,
SP.CountryRegionCode
FROM Employee AS E
LEFT JOIN Contact AS C ON E.ContactID=C.ContactID
LEFT JOIN EmployeeDepartmentHistory AS EDH ON EDH.EmployeeID=E.EmployeeID
LEFT JOIN Department AS D ON D.DepartmentID=EDH.DepartmentID
LEFT JOIN Employee AS Manager ON Manager.EmployeeID.=E.ManagerID
LEFT JOIN Contact AS M ON Manager.ContactID=M.ContactID
LEFT JOIN (SELECT EmployeeID, AddressID, MAX(ModifiedDate) FROM [Employee Address] GROUP BY EmployeeID, AddressID) AS EA ON E.EmployeeID=EA.EmployeeID
LEFT JOIN Address AS A ON EA.AddressID=A.AddressID
LEFT JOIN StateProvince AS SP ON SP.StateProvinceID=A.StateProvinceID
WHERE EDH.EndDate IS NULL
AND A.City='New York'