Partition Data to Find the Most Recent Record in SQL Server 2005/2008

A user had a requirement where he wanted to find out the most recent OrderDate in a table, grouped by Customers. The data contained information like OrderDate, Price and ProductId purchased by Customers. In order to find the most recently placed order for each Customer, you can partition the data as shown below:

Sample Data


DECLARE @TT table(CustID int, ProductID int, OrderDate datetime, Spending decimal(10,3))


INSERT @TT 


SELECT 1133, 100 , '04/28/2009', 5.03 UNION ALL


SELECT 1431, 103 , '04/28/2009', 19.02 UNION ALL


SELECT 1431, 105 , '04/28/2009', 15.00 UNION ALL


SELECT 1133, 100 , '04/29/2009', 13.40 UNION ALL


SELECT 1142, 105 , '04/29/2008', 14.60 UNION ALL


SELECT 1142, 103 , '04/29/2008', 11.70 UNION ALL


SELECT 1133, 100 , '04/29/2008', 18.60 




Query


-- Find Most Recent Order for each Customer


SELECT Custid, Spending, OrderDate FROM


(


SELECT CustID, Spending, OrderDate, ROW_NUMBER() OVER


(PARTITION by CustID ORDER BY OrderDate) AS custGrp


FROM @TT


) AS Tot


WHERE custGrp = 1




Results


Custid    Spending    OrderDate


1133    18.600    2008-04-29 00:00:00.000


1142    14.600    2008-04-29 00:00:00.000


1431    19.020    2009-04-28 00:00:00.000



About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Josi said...

Hi Suprotim Agarwal,

The query you posted retrieves the first order placed by the customer. In order to retrieve the most recent you should add the keyword DESC to the order by in the ROW_NUMBER.
something like:
ORDER BY OrderDate DESC

Cheers,
Jose

Suprotim Agarwal said...

Thanks Jose. That makes a lot of sense!