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 find the 5 largest orders for each customer?

Execute the following Microsoft SQL Server T-SQL example script in Management Studio Query Editor to demonstrate listing of the top 5 orders for each customer.

-- SQL find top n records - T-SQL row number over partition by

USE AdventureWorks;

GO

DECLARE @n tinyint

SET @n = 5

SELECT   Customer,

         SalesOrderID,

         -- MSSQL format currency (money)

         DollarAmount = '$'+LEFT( convert(varchar,DollarAmount,1),

                                len(convert(varchar,DollarAmount,1))-3)

FROM     (SELECT Customer = s.Name,

                 soh.SalesOrderID,

                 DollarAmount = soh.TotalDue,

                 SequenceNumber = ROW_NUMBER()

                 OVER(PARTITION BY soh.CustomerID ORDER BY soh.TotalDue DESC)

          FROM   Sales.SalesOrderHeader AS soh

                 INNER JOIN Sales.Store s

                   ON soh.CustomerID = s.CustomerID) t

WHERE    t.SequenceNumber <= @n

ORDER BY Customer

GO

 

/* Partial results

 

Customer                SalesOrderID      DollarAmount

A Bike Store            45283             $37,643

A Bike Store            46042             $34,722

A Bike Store            44501             $26,128

A Bike Store            43860             $14,603

A Great Bicycle Company 44125             $3,450

A Great Bicycle Company 44793             $2,828

A Great Bicycle Company 45569             $2,828

A Great Bicycle Company 46378             $2,224

A Great Bicycle Company 49537             $622

A Typical Bike Shop     46343             $39,156

A Typical Bike Shop     44755             $37,725

A Typical Bike Shop     45536             $28,429

A Typical Bike Shop     44092             $5,440

*/

----------

 

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.