Select the top value for a given parent record in a child databas.

D

Dwise

I have a "parent database" of contacts and a "child" database of phone calls.
How do I create a query that shows parent records and only the latest
"calls" as contained in the corresponding linked record in the child database?
 
J

John Spencer (MVP)

It depends, do you have something in the child database that shows the datetime
of the last phone call? And what do you want returned? The date and time of
the last call, additional information?

SELECT C.FieldA, C.FieldB, Max(CallDate) as LastCall
FROM Contacts as C INNER JOIN PhoneCalls as P
 
D

Dwise

Thank you. Yes the child database has date and time fields and I want to
display one other text field from the Parent and child database. Based on
your suggestion, is the following correct?

SELECT Contacts.ContactID, Max(Calls.CallDate) AS MaxOfCallDate,
First(Calls.Subject) AS FirstOfSubject
FROM Contacts LEFT JOIN Calls ON Contacts.ContactID = Calls.ContactID
GROUP BY Contacts.ContactID;
 
J

John Spencer (MVP)

No, it isn't. First will basically return a more or less random value from the
subject field that is one of the ones available for this contact.

In this case, you can use a subquery

SELECT Contacts.ContactID, Calls.CallDate,
Calls.Subject
FROM Contacts LEFT JOIN Calls
ON Contacts.ContactID = Calls.ContactID
WHERE Call.CallDate =
(SELECT Max(C.CallDate)
FROM Contacts C
WHERE C.ContactID = Contacts.ContactID)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top