I'm having trouble wrapping my head around what should be a pretty simple query in MS SQL. I have two tables: Employees
and Departments
.
Employees
consists of the standard items: ID (pkey int)
, FName
, LName
, ... , DepartmentID
.
Departments
consists of DepartmentID
, DepartmentName
, ... , ManagerID
.
There is a relationship from Employees.DepartmentID
to Departments.DepartmentID
, and a relationship between Departments.ManagerID
and Employees.EmployeeID
.
In other words, each employee has a department, and each department has a manager that is also an employee.
I'm trying to create a view that will display the employee name, ... , department, and department manager.
I keep getting an error that more than one value is being returned when using this code:
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
Any ideas on how to join back to the same table (different row) based on the relationship from a second table?