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 apply CROSS APPLY for high-end sales analysis?

Execute the following Microsoft SQL Server T-SQL script in Management Studio Query Editor to demonstrate the use of CROSS APPLY for high-end (over $3,000) mountain bike sales analysis. First, a table-valued user-defined function (UDF) is created to serve as the righthand-side of the CROSS APPLY.

USE AdventureWorks2008;

 

GO

 

CREATE FUNCTION dbo.fnGetProductSalesRunningTotal

               (@ProductID    INT,

                @SalesOrderID INT)

RETURNS @SalesRunningTotal TABLE(SalesTotal MONEY,

                                 SalesCount INT)

  BEGIN

    INSERT INTO @SalesRunningTotal

               (SalesTotal,

                SalesCount)

    SELECT SUM(LineTotal),

           SUM(OrderQty)

    FROM   Sales.SalesOrderDetail

    WHERE  ProductID = @ProductID

           AND SalesOrderID <= @SalesOrderID

    

    RETURN

  END

 

GO

 

SELECT   ProductName = p.Name,

         OrderDate = convert(CHAR(10),OrderDate,111),

         SalesTotal = '$' + convert(VARCHAR,SalesTotal,1),

         SalesCount

FROM     Sales.SalesOrderDetail sod

         JOIN Production.Product p

           ON p.ProductID = sod.ProductID

         JOIN Sales.SalesOrderHeader soh

           ON soh.SalesOrderID = sod.SalesOrderID

         CROSS APPLY dbo.fnGetProductSalesRunningTotal(sod.ProductID,sod.SalesOrderID)

WHERE    p.Name LIKE '%Mountain%'

         AND UnitPrice > $3000

ORDER BY p.Name ASC,

         OrderDate,

         soh.SalesOrderID

/* ProductName    OrderDate   SalesTotal  SalesCount

Mountain-100 Black, 38  2001/07/28  $47,924.86  23

Mountain-100 Black, 38  2001/07/30  $51,299.85  24

Mountain-100 Black, 38  2001/07/30  $54,674.84  25

Mountain-100 Black, 38  2001/08/09  $194,362.97 94   .....*/

 

Related article:

 

http://www.sqlusa.com/articles2005/crossapply/

 

 

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.