I have a database table which stores membership renewals each year. When insert the renewal record, an ‘expiryDate’ column is written with a date (31/8/[nextyear]).
So, as an example, let’s say a member with memberID = 99 renews in 2007, 2008 and 2009, he will have 3 records (one for each year), with an ‘expiryDate’ recorded in each. If I do a
SELECT MAX(YEAR(expiryDate)) as maxExpiry
FROM renewals
WHERE memberID = 99
…I will get 2010 back.
What I would like to do is return ALL records where the MAX(YEAR(expiryDate)) is a given year.. for example,
SELECT *
FROM renewals
WHERE MAX(YEAR(expiryDate)) = '2010';
This query won’t work as an aggregation can’t be used in a where clause outside a subquery, but I can’t quite work out how to structure the subquery… or even if this could be done a better way than using a subquery.
A predicate based on an aggregated column uses a
HAVINGclause, rather than aWHERE.If you only need the memberID, this is straightforward enough:
You can also do this as a sub-query if you need to get other columns from that table, ie:
UPDATE
It is correct as @OMG Ponies pointed out that this is not enough if you need to select additional columns from that one row in
renewals. If that is required, you could use: