Heres a short exmaple to get you thinking about how query results can be joined to tables for purposes such as attaching summary data.
The example below shows how a query that sums total sales for a product can be joined to a query that selects product ID and product name from the Products table in Microsoft's Adventure Works sample database.
SELECT
PROD.ProductID,
PROD.[Name],
ISNULL(SALES.ProductSales,0) ProductSales
FROM Production.Product PROD
LEFT JOIN
(
SELECT ProductId,
SUM(LineTotal) ProductSales
FROM Sales.SalesOrderDetail SOD
GROUP BY ProductID
) SALES
ON PROD.ProductID = SALES.ProductID
The SELECT query within the parentheses returns a result with two columns: 1) ProductID and 2) ProductSales.
The query within parentheses is assigned the alias 'SALES' which is used to construct the ON clause that joins SALES to the Product table.
Because the SALES query returns ProductID (SALES.ProductID) it can be joined to PROD.ProductID.
Mike McIntyre's .Net Journal
getdotnetcode.com