SQL aggregate function

T

Tim Ferguson

Dear All

This is not strictly a tables/ db design question, but I have friends and
experts I trust here!

I have a table of subscriptions paid to a society:

Subs(*MemberNum, *YearNum, CategoryType, PaidAmount, PaidDate, etc)

Now, if I want to get the most recent year that a member paid, it's
simple:

SELECT MemberNum, MAX(YearNum) AS CurrentYear
FROM Subs
GROUP BY MemberNum

but if I want to retrieve (say) the membership type in that year it's not
so easy:

SELECT MemberNum, Max(YearNum), First(CategoryType)
FROM Subs
GROUP BY MemberNum

does not retrieve values from the same record. I know I can do it with a
subselect and a join

SELECT o.MemberNum, o.YearNum, o.CategoryType
FROM Subs AS o
RIGHT JOIN
( SELECT MemberNum, MAX(YearNum) AS CurrentYear
FROM Subs
GROUP BY MemberNum
) AS i
ON i.MemberNum = o.MemberNum
AND i.CurrentYear = o.YearNum


but it seems that there should be a simpler way. What am I missing?

All the best


Tim F
 
T

Tim Ferguson

With a 'history' table (more correctly a 'valid-time' state table) it
is very common to have a 'current' VIEW (stored Query) expressly to
avoid having to write a subquery each time.

Point taken. Thanks Jamie.


Tim F
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top