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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Max aggregate function in Query

Status
Not open for further replies.

DaveTappenden

Programmer
Jan 16, 2002
21
0
0
Please help, I have a severe case of brain fade!.

I am trying to create a query based on 2 tables using an inner join, but only selecting the record in the 2nd table with the highest value (Invoice Number).

The following query will give me all Invoices for a customer:
SELECT Cust.CustName, Inv.InvNr
FROM Cust INNER JOIN Inv ON Cust.CustID = Inv.CustID
WHERE (((Cust.CustName)="Smith"));

- but I only want to extract a single row from the 2nd table, which is the last (highest) invoice number.
So, I add the Max aggregate function:

SELECT Cust.CustName, MAX(Inv.InvNr)
FROM Cust INNER JOIN Inv ON Cust.CustID = Inv.CustID
WHERE (((Cust.Name)="Smith"));

However, this causes the query to fail with an Access error "You have tried to execute a query that does not include the specified expression 'CustName' as part of an aggregate function"

Can any kind person explain what I am doing wrong please?

Thanks.
David
 
If you aggregate any one column in the query, you need to aggregate them all. You could add a group by to customer name and that would fullfil the rule.

WHERE (((Cust.Name)="Smith"))
group by Cust.Name
 
What about using a subquery in your WHERE clause....I haven't tested the query, but would something like this work?

SELECT Cust.CustName, Inv.InvNr
FROM Cust INNER JOIN Inv ON Cust.CustID = Inv.CustID
WHERE (((Cust.Name) = "Smith") AND (Inv.invNr)=(SELECT max(invNR) from [Inv] WHERE CustID = Cust.CustID)));

JJ

J. Jones
jjones@cybrtyme.com
 
Hi!

Another possibility would be:

SELECT Top 1 Cust.CustName, Inv.InvNr
FROM Cust INNER JOIN Inv ON Cust.CustID = Inv.CustID
WHERE (((Cust.Name)="Smith"))
Order By Inv.InvNr;

hth
Jeff Bridgham
bridgham@purdue.edu
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top