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

SQL query: Fetch Employee Name (i.e. FirstName space LastName), Department Name, Manager, City, StateProvinceCode, CountryRegionCode

条件:城市所在的地方 'New York'。如果 Manager 为 NULL,则显示 'CEO'。 我分享了 table 结构的 link。

我知道我可以通过子查询、CTE 或自连接来实现这一点。但我是 CTEs/Self 加入的新手,因此需要一些帮助。

正在尝试如下操作:但我很困惑该怎么做。

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) 通过在 Employee table

中查找 ManagerID 和 EmployeeID 找到经理

2) 历史上的员工可能曾在多个部门工作,而您只查找当前员工,因此 EndDate in EmployeeDepartmentHistory IS NULL

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'