SQL Server 2008 - Get Latest Record from Joined Table

Posted by user336786 on Stack Overflow See other posts from Stack Overflow or by user336786
Published on 2010-05-10T15:58:07Z Indexed on 2010/05/10 16:14 UTC
Read the original article Hit count: 142

Filed under:

Hello,

I have a SQL Server 2008 database. This database has two tables called Customer and Order. These tables are defined as follows:

Customer
--------
ID,
First Name,
Last Name

Order
-----
ID,
CustomerID,
Date,
Description

I am trying to write a query that returns all of the customers in my database. If the user has placed at least one order, I want to return the information associated with the most recent order placed. Currently, I have the following:

SELECT
  *
FROM
  Customer c LEFT OUTER JOIN Order o ON c.[ID]=o.[CustomerID]

As you can imagine, this will return all of the orders associated with a customer. In reality though, I only want the most recent one. How do I do this in SQL?

Thank you!

© Stack Overflow or respective owner

Related posts about sql-server