I have an Address History table with three fields: EmpID, Address, AddrID.
Every time I add a new address, I also increment the Address ID (AddrID) by 1 for that particular employee.
EmpID | AddrID | Address
-------------------------------
1 | 1 | 1234 First Ave
1 | 2 | 2145 First Ave
1 | 3 | 1111 First Ave
2 | 1 | 1001 Second St
2 | 2 | 1002 Second St
2 | 3 | 1003 Second St
2 | 4 | 2222 Second St
3 | 1 | 3332 Third Lane
3 | 2 | 3333 Third Lane
4 | 1 | 4444 Fourth Way
How do I get the most recent address (highest Address ID) for each employee? Ideally, I should be able to return:
EmpID | AddrID | Address
-------------------------------
1 | 3 | 1111 First Ave
2 | 4 | 2222 Second St
3 | 2 | 3333 Third Lane
4 | 1 | 4444 Fourth Way
So far I have either returned too many results (ie, every Employee, every AddrID 1, and every Address associated with the two), or too few results (ie, every Employee with an AddrID 4 – just Employee 2).
I have tried using Distinct, Group By, Order By, Having, and Self-Joins to no avail.
What am I missing?
You can use a subquery that gets the
MAX()addrid for each empid:See SQL Fiddle With Demo
The inner query will return the max
addridand theempidthen you join your table to that result on those two values this will limit the records that get returned.