Create Table Employees: Emp - Id Emp - Name Emp - Manager - Id
Create Table Employees: Emp - Id Emp - Name Emp - Manager - Id
Because this query involves a join of the ProductVendor table with itself, the
ProductVendor table appears in two roles. To distinguish these roles, you must give the
ProductVendor table two different aliases (pv1 and pv2) in the FROM clause. These
aliases are used to qualify the column names in the rest of the query. This is an example
of the self-join Transact-SQL statement:
Copy
USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2
ON pv1.ProductID = pv2.ProductID
AND pv1.VendorID <> pv2.VendorID
ORDER BY pv1.ProductID
For self join in sql you can try the following example:
Now to get the names of managers from the above single table you can use sub queries or
simply the self join.
Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id
Result:
manager employee
John Tom
John Smith
Tom Albert
Tom David
David Murphy
David Petra
In the above self join query, employees table is joined with itself using table aliases e1
and e2. This creates the two views of a single table.