SQL查询:获取员工姓名(即FirstName空间LastName),部门名称,经理,城市,StateProvinceCode,CountryRegionCode

时间:2017-08-06 19:44:39

标签: sql join common-table-expression self-join

条件:城市是'纽约'。如果Manager为NULL,则显示“CEO”。 我已经分享了表结构的链接。

Table Structure/Schema Diagram

我知道我可以通过子查询,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;

无法继续进行。请帮忙......

1 个答案:

答案 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'