Reputation: 149
So I been struggling with this one for a while. The question is as follows:
Find all the Employees to whom no other employee reports to. Print the Id, and the first and last name of such employees.
The Relationship Sets can be found here:
https://chinookdatabase.codeplex.com/wikipage?title=Chinook_Schema&referringTitle=Documentation
And the Data in the Table is as follows (Note that the rest of the data that is cut off is not needed)
Now, the easiest solution that I immediately saw was that the Sale Support had no one report to them:
Select DISTINCT E.EmployeeId, E.FirstName, E.LastName
From Employee E
Where E.Title = 'Sales Support Agent'
But that seems like a cheap work around, is there a way to get the answer using EmployeeID and ReportsTo only?
Upvotes: 1
Views: 1024
Reputation: 874
This should give you what you are wanting:
Select
E.EmployeeId
,E.FirstName
,E.LastName
From Employee E
Where E.EmployeeID NOT IN (SELECT DISTINCT ReportsTo
FROM Employee
WHERE ReportsTo is not null)
Selects every employee that has no one who reports to them.
Upvotes: 1
Reputation: 201
This should work:
Select E.EmployeeId, E.FirstName, E.LastName
From Employee E
Where E.EmployeeID NOT IN (SELECT ReportsTo FROM Employee WHERE ReportsTo IS NOT NULL)
Upvotes: 1
Reputation: 48187
SELECT E.*
FROM Employee E
LEFT JOIN Employee R -- R for report to
ON E.EmployeeID = R.ReportTo
WHERE R.EmployeeID IS NULL
OUTPUT
| EmployeeID | LastName | ReportTo |
|------------|----------|----------|
| 3 | Peacock | 2 |
| 4 | Park | 2 |
| 5 | Johnson | 2 |
| 7 | King | 6 |
| 8 | Callahan | 6 |
Upvotes: 4