Full Version: Return "Last" date using grouping in query
UtterAccess Discussion Forums > Microsoft® Access > Access Queries
kendy60
I have a table with Item Number, NDC number, Invoice Date, Unit Cost, Item Description, and several other fields. There are multiple records for each Item Number because the price may have changed, and there would be different Unit Cost entries. All I want to do is pull out the last invoice date and price.However - I am not getting the "Last" price. I have done this before - and cannot figure out why it is not working now! I even went back to basics - creating a new query with only Invoice Date, item description, and NDC number. It returns a date - but not the last one...
ideas???

Thanks!
freakazeud
Hi,
Welcome to UA forums.
create a totals query on the date field in the totals criteria use MAX! The LAST option can be very unreliable, so use max.
This should give you the last date entered for the invoice and all it's information in the record!
HTH
Good luck
mishej
This is a tricker query to create using the Query grid. This type of query is more easily done in SQL using a subquery - actually a "correlated subquery".

You can use the Max() SQL aggregate function to get the latest Invoice Date FOR ALL RECORDS. But when you want to get the latest value for a "group" then you'll need the correlated sub-query.

The Last() aggregate function does not do this! Its usefulness is extremely limited.

I suspect the query you need looks something like this:
CODE
SELECT [Item Number], [NDC number], [Invoice Date], [Unit Cost], [Item Description]
FROM [color="red"]yourTableNameHere[/color] y
WHERE [Item Number] = (
                       SELECT TOP 1 [Item Number]
                       FROM [color="red"]yourTableNameHere[/color]
                       WHERE [Item Number] = y.[Item Number] ORDER BY [Invoice Date] DESC
                      )
ORDER BY [Item Number];


replace the red text with your table name.

As an aside, it is not good database design to have all this info in one table. It would appear that the fields:
[NDC number], [Invoice Date], [Unit Cost], [Item Description]
are all dependent on the [Item Number] field and thus should be in an "Items" table.

Also, field names with spaces on them are frowned upon since they often cause difficult-to-resolve issues in Access.
kendy60
Guys - I can't thank you enough! I think the Max is going to work - but I'm going to create a "correlated subquery" too to try it that way. So glad I found this forum - I needed an answer fast and I SURE DO appreciate it!

Thanks!
Kendy
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.