Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Microsoft: Access Queries and JET SQL FAQ


Correlated Subqueries by Norris68
Posted: 22 Aug 03

A frequent question posted on here is something like "How do I list all of my customers along with their most recent order". You can achieve this using a correlated subquery. A correlated subquery is a query within a query that references or 'correlates' with the outer query.

SELECT CustomerID,
(SELECT TOP 1 OrderID FROM Orders WHERE CustomerID=C.CustomerID ORDER BY OrderDate DESC) AS LastOrderID
FROM Customers C

Note that we alias the outer query - in this case it is called 'C'. The subquery pulls the most recent order, matching the CustomerID from the outer query.

Another example with an INNER JOIN in the subquery:
SELECT CustomerID,
(SELECT TOP 1 Orders.OrderID FROM Orders INNER JOIN OrderItems ON Order.OrderID = OrderItems.OrderID WHERE Orders.CustomerID=C.CustomerID AND OrderItems.ItemID=6 ORDER BY Orders.OrderDate DESC) AS LastOrderID
FROM Customers C

This will produce a list of all customers along with the most recent order they placed for Item number 6.

Back to Microsoft: Access Queries and JET SQL FAQ Index
Back to Microsoft: Access Queries and JET SQL Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close