Bagikan melalui


Using Self-Joins

A table can be joined to itself in a self-join. Use a self-join when you want to create a result set that joins records in a table with other records in the same table. To list a table two times in the same query, you must provide a table alias for at least one of instance of the table name. This table alias helps the query processor determine whether columns should present data from the right or left version of the table.

Examples

A. Using a self-join to find the products supplied by multiple vendors

The following example uses a self-join to find the products that are supplied by more than one vendor.

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:

USE AdventureWorks2008R2;
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

B. Using a self-join to match sales people and their territories

The following example performs a self-join of the Sales.SalesPerson table to produce a list of all the territories and the sales people working in them.

SELECT st.Name AS TerritoryName, sp.BusinessEntityID, 
    sp.SalesQuota, sp.SalesYTD
FROM Sales.SalesPerson AS sp
    JOIN Sales.SalesTerritory AS st
        ON sp.TerritoryID = st.TerritoryID
ORDER BY st.Name, sp.BusinessEntityID