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 ROW_NUMBER in a CTE (Common Table Expression)?

Execute the following Microsoft SQL Server Transact-SQL (T-SQL) script in Management Studio (SSMS) Query Editor, SQLCMD or other client software to demonstrate the use of ROW_NUMBER function with PARTITION BY. The TOP 10 selects the largest orders for each customer.

USE AdventureWorks

GO

 

 

WITH cteTotalDueSorted

AS

(

SELECT

      Customer = s.Name,

      s.CustomerID,

      SalesOrderID,

      OrderDate,

      TotalDue='$'+convert(varchar,TotalDue,1),

      SeqNo = ROW_NUMBER() OVER (

                                       PARTITION BY soh.CustomerID

                             ORDER BY TotalDue DESC)

FROM  Sales.SalesOrderHeader AS soh

JOIN Sales.Store s

  ON soh.CustomerID = s.CustomerID

)

 

SELECT

      Customer,

      ItemNo=cte.SeqNo,

      SalesOrderID,

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

      TotalDue

FROM cteTotalDueSorted cte

WHERE cte.SeqNo <= 10

ORDER BY CustomerID, ItemNo

 

Partial Results:

Customer ItemNo SalesOrderID OrderDate TotalDue
A Bike Store 1 45283 2002/2/1 $31,972.17
A Bike Store 2 46042 2002/5/1 $29,418.53
A Bike Store 3 44501 2001/11/1 $22,152.24
A Bike Store 4 43860 2001/8/1 $12,381.08
Progressive Sports 1 46976 2002/8/1 $8,727.11
Progressive Sports 2 47997 2002/11/1 $4,682.69

 

 

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.