in

vbCity Blogs

New (temp) place for vbCity Blogs

Mike McIntyre's .NET Journal

SQL Join Summary Query Example

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

Only published comments... Nov 04 2009, 06:57 PM by Mike McIntyre
Filed under: , ,

About Mike McIntyre

I  am a programmer, developer, and system architect with 29+years experience including state-of-the-art application development frameworks and languages including Visual Studio versions 2002-2010, .NET Framework versions 1-4, C#, and Visual Basic.

I am a mentor, trainer, and coach in the Microsoft .NET technical community. DevCity is my favorite community site. You can find examples of my involvement with DevCity in the site articles, newsletter articles, and my posts in the forum.

Since 2002 I have hosted a .NET site at http://www.getdotnetcode.com, a place with free and inexpensive Visual Basic and C# source code that can be purchased on an 'as needed' basis.

In 2007 I established a .NET search engine, 'Resources for .NET Developers' at http://dot-net-resources-swicki.eurekster.com

Copyright 1998-2009 vbCity.com LLC
Powered by Community Server (Non-Commercial Edition), by Telligent Systems