Adam Boyle
Adam Boyle

Reputation: 89

Access Database Query Grouping

I have an Access 2003 database I've been asked to try and amend. My MS Access skills are limited hence this question.

The query looks like this:

SELECT
  TBL_PropertyProgramMember.PropertyId,
  Max(TBL_PropertyProgramMember.To) AS MaxOfTo,
  TBL_PropertyProgramMember.BookingPriority
FROM
  TBL_PropertyProgramMember
GROUP BY
  TBL_PropertyProgramMember.PropertyId,
  TBL_PropertyProgramMember.BookingPriority;

I need to return unique PropertyIds, the maximum To value for each property, and the BookingPriority associated with that maximum To value. Using the above grouping, I get multiple results if there property is listed more than once with different a different BookingPriority.

As I'm using grouping, I can't remove the BookingPriority grouping without Access throwing an error.

I'm sure this is to do with grouping, but I can't work out how to fix it. Just getting the maximum or minimum BookingPriority won't fix the problem because the value can change.

Upvotes: 0

Views: 108

Answers (1)

Lord Peter
Lord Peter

Reputation: 3501

You have to compute your maximum (without returning your BookingPriority) and then join back to the results again, something like this:-

SELECT 
TBL_PropertyProgramMember.PropertyID, 
M.MaxTo, 
TBL_PropertyProgramMember.BookingPriority

FROM 
(
SELECT 
TBL_PropertyProgramMember.PropertyID, 
Max(TBL_PropertyProgramMember.To) AS MaxTo
FROM 
TBL_PropertyProgramMember
GROUP BY 
TBL_PropertyProgramMember.PropertyID
) AS M 
INNER JOIN 
TBL_PropertyProgramMember 
ON (M.MaxTo = TBL_PropertyProgramMember.To) 
AND (M.PropertyID = TBL_PropertyProgramMember.PropertyID);

You will need to handle cases where there is more than one record having the same maximum "To" column for a given BookingPriority.

Upvotes: 2

Related Questions