Select the max date that is less than another specific date

I have one database with Equipment ID’s and multiple Transaction Dates per ID:

Equipment ID    Transaction Date

7557545                09/30/2016

7557545                05/24/2016

7557545                03/01/2016

7557545                12/13/2016

2112353                08/17/2016

2112353                07/24/2016

2112353                06/01/2016

 

I need to create a query to select the max date closest to (less than) a specific date, such as 6/30/2016 (the result would be the transaction dates bolded in the examples above).  This would be really easy to do with two tables (use one to select all transactions less than 6/30/2016, then take that result and create another table select the max date grouped by Equipment ID.  But the database has way too many lines to use this approach – there’s simply too much data.  I need to find a way to do this in one query.

 

I set-up my query as follows:

                                               

Field:                    Equipment ID    Transaction Date             

Table:                   Database TableDatabase Table

Total:                    Group By             Max

Sort:                     

Show:                            þ                            þ

Criteria:                                               < “6/30/2016”

 

This doesn’t work because the Max selects the max date, regardless of whether or not it’s greater than 6/30/2016, then the Criteria eliminates it.  So for the example at top, nothing would show for ID 7557545 because the 9/30 date is selected by Max, then eliminated by the Criteria.  Any suggestions on how to correct this would be greatly appreciated!!

Answer
Answer
The way you have set it up in query design view creates a HAVING clause in the query, which operates on the aggregated values.  You should use a WHERE clause to restrict the query before aggregation.  Also, the delimiter for a date literal is the # character, not a quotes character:

SELECT [Equipment ID], MAX([Transaction Date]) AS LatestDate
FROM [Database Table]
WHERE [Transaction Date] < #2016-30-06#
GROUP BY [Equipment ID];

The date literal here uses the ISO standard format for date notation of YYYY-MM-DD to make it internationally unambiguous.  The US format of MM/DD/YYYY can also be used, as this is the default format used by JET/ACE SQL.
_____________________
Ken Sheridan,
Newport, Shropshire, England

"Don't write it down until you understand it!" - Richard Feynman

3 people found this reply helpful

·

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated March 20, 2024 Views 10,034 Applies to: