SQLUSA

Microsoft SQL Server 2008 Best Practices

How to use SQL self-join?

 

Execute the following T-SQL script in Query Editor to demonstrate the use of self-join on the ProductVendor table to find products with multiple vendors:

USE AdventureWorks;

GO

SELECT DISTINCT

      ProductName=p.Name,

      ProductNumber,

      Vendor=v.Name

FROM Purchasing.ProductVendor pv1

-- This is a self-join

INNER JOIN Purchasing.ProductVendor pv2

      ON pv1.ProductID = pv2.ProductID

      AND pv1.VendorID != pv2.VendorID

INNER JOIN Production.Product p

      ON pv1.ProductID = p.ProductID

INNER JOIN Purchasing.Vendor v

      ON pv1.VendorID = v.VendorID

ORDER BY

      ProductName,

      Vendor

GO   

SQLUSA - The Best SQL Server 2008 Training in the World
 
 
SQLUSA.com Home Page