简体   繁体   中英

SQL select record for each id where max year equals value

There is a lot of info on this but nothing seems to match my issue exactly and I am stuck.

I have two tables, 'members' and 'payment_records'. The 'members' table includes a unique member_id as well as other data (address, payment_type etc). The 'payment_records' table includes a unique payment_id, plus the member_id relative to who made the payment, and an expiry_year (eg 2011, 2012, 2013 etc). Each member_id has multiple payment records.

I need to get the records where the MAXIMUM expiry_year for each member_id matches a dynamic value ($year). Right now I am returning records where all members have an expiry_year = $year, even if it's not the MAXIMUM value. For example, Mary might have 2 payments with expiry years of 2013 and 2014, so she shows in my results for $year = 2013, even though her most recent result is 2014. How do I limit it so records are only returned if the maximum expiry_year is = $year?

This is my (simplified) statement now, that returns records with the correct expiry, but doesn't weed out the ones with a newer year:

SELECT members.member_id, payment_records.expiry_year, payment_records.member_id
        FROM members inner join payment_records on members.member_id=payment_records.member_id
        WHERE member_category='Standard' AND payment_records.expiry_year = $year"

I have tried using a sub statement but am confused as to the correct syntax in amongst my inner join statement. I've also tried using DISTINCT and GROUP BY with ORDER BY but it just gives me blank results.

Any help is appreciated in advance. I am sorry if this is a double-up, I've been searching tutorials till my eyeballs ached with no luck.

You want to use group by and having for this logic:

SELECT members.member_id, MAX(pr.expiry_year)
FROM members m inner join
     payment_records pr
     on m.member_id = pr.member_id
WHERE m.member_category = 'Standard'
GROUP BY m.member_id
HAVING MAX(pr.expiry_year) = $year;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM