Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pull most recent rows per customer 1

Status
Not open for further replies.

Glasgow

IS-IT--Management
Jul 30, 2001
1,669
GB
Suppose I have an Orders table with 3 fields: CustomerId, OrderDate and OrderAmount. There can be several orders per customer.

How would I write a SELECT query that just returned the most recent row (i.e. highest OrderDate value) for each customer? So, if there were 100 customers with 3 orders per customer (300 rows in all), the query would return the 100 most recent orders?

I'm sure it should be easy but I just can't get there!

Thanks in advance.
 
Code:
SELECT a.*
FROM Orders a
INNER JOIN 
  (SELECT CustomerID, MAX(OrderDate) AS MaxDate FROM Orders b GROUP BY CustomerID) c
ON a.CustomerID = c.CustomerID AND a.OrderDate = c.MaxDate
 
Yep that does it, thank you.
 
Using sql2005....

SELECT a.* FROM (
SELECT customerID, OrderDate, ROW_NUMBER() OVER (PARTITION BY customerID ORDER BY OrderDate DESC) AS RecID FROM Orders
) AS a WHERE RecID = 1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top