SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to use derived tables to build complex queries?

The following Microsoft SQL Server T-SQL sample script demonstrates the application of derived table (cnum) to build complex queries:

-- SQL derived table - subselect - inner join subselect

USE Northwind;

SELECT   c.CategoryName,

         p.ProductName,

         p.UnitPrice,

         cnum.NoOfProducts

FROM     Categories c

         INNER JOIN Products p

           ON c.CategoryID = p.CategoryID

         INNER JOIN (SELECT   c.CategoryID,

                              NoOfProducts = count(* )

                     FROM     Categories c

                              INNER JOIN Products p

                                ON c.CategoryID = p.CategoryID

                     GROUP BY c.CategoryID) cnum  -- derived table - subselect

           ON c.CategoryID = cnum.CategoryID

ORDER BY c.CategoryName

GO

/* Partial results

 

CategoryName      ProductName             UnitPrice   NoOfProducts

Beverages         Chai                    18.00       12

Beverages         Chang                   19.00       12

Beverages         Guaraná Fantástica      4.50        12

Beverages         Sasquatch Ale           14.00       12

Beverages         Steeleye Stout          18.00       12

Beverages         Côte de Blaye           263.50      12

*/

------------

 

Related articles:

Using Derived Tables to Simplify the SQL Server Query Process

SQL Server 2005 Derived Tables, Common Table Expressions and Indexed Views Query Processing Part II

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.