I need a query that will produce a non duplicate list of all of our members and their corresponding states & countries (along with some other data that is joined from other tables). Each member may have 0-many MemberAddress records. If a member has MemberAddress records, I would like to join only to the record that has been modified most recently. If the member does not have any associated MemberAddress records, I still want the member to show in the list, but the state and country would then be NULL values.
SELECT m.member, ma.state, ma.country FROM Member m
LEFT OUTER JOIN MemberAddress ma ON m.member = ma.member
INNER JOIN (SELECT Member, MAX(Modified) AS MaxDate
FROM MemberAddress
GROUP BY Member) AS m2
ON (ma.Member = m2.Member AND ma.Modified = m2.MaxDate)
This query removes the duplicates caused when a member has multiple MemberAddress records, however it does not allow for members that do not have any MemberAddress records.
How can I alter this query to also show members that do not have any MemberAddress records?
Thanks!!
Edited to add: I'm using SQL 2005
Your version is quite close. You can do it using two left joins:
You were on the right track, but the join between ma and m2 has to, itself, be an entire subquery. The problem is that your INNER JOIN applies to the whole query, not just to the relationship between ma and m2:
Assuming I didn't typo anything (except that parentheses, which I fixed).
You can try using
Row_Number
to get the rows with the max date:I'm writing this syntax from memory but I think this will work.
something like below ought to work (untested)
You're very close already. This just needs your
INNER JOIN
to becomeLEFT JOIN
as you did betweenMember
andMemberAddress
. The inner join is causing rows to drop as you have it now.The answers including the
OVER
clause are also perfectly legit. There's an MSDN Article for more information on that approach.Update: adding the query that worked for me: