SQLUSA
Free Trial Save on Combos

SQL Server 2008 Best Practices
SQL Server 2005 Best Practices
SQL Server 2000 Best Practices

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

*/

----------

 

American Standard in SQL Server 2008 Training
 
 
SQLUSA.com Home Page