我很难理解 MS SQL 中应该是一个非常简单的查询。我有两张桌子:Employees
和Departments
。
Employees
由标准项目组成:ID (pkey int)
, FName
, LName
, ... , DepartmentID
.
Departments
由DepartmentID
, DepartmentName
, ... ,ManagerID
组成
从Employees.DepartmentID
到有关系,和Departments.DepartmentID
之间有关系。Departments.ManagerID
Employees.EmployeeID
换句话说,每个员工都有一个部门,每个部门都有一个经理,他也是一个员工。
我正在尝试创建一个显示员工姓名、...、部门和部门经理的视图。
使用此代码时,我不断收到一个错误,即返回了多个值:
SELECT
Employees_1.EmployeeID, Employees_1.FirstName, Employees_1.LastName,
Departments_1.DepartmentName,
(SELECT
dbo.Employees.LastName
FROM dbo.Employees
INNER JOIN dbo.Departments
ON dbo.Departments.DepartmentManager = dbo.Employees.EmployeeID
) AS ManagerName
FROM dbo.Employees AS Employees_1
INNER JOIN dbo.Departments AS Departments_1
ON Employees_1.Department = Departments_1.DepartmentID
AND Employees_1.EmployeeID = Departments_1.DepartmentManager
关于如何根据第二个表的关系连接回同一个表(不同的行)的任何想法?