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:
select t1.empid,
t1.addrid,
t1.address
from table1 t1
inner join
(
select max(addrid) addrid, empid
from table1
group by empid
) t2
on t1.empid = t2.empid
and t1.addrid = t2.addrid
See SQL Fiddle With Demo
The inner query will return the max addrid and the empid then you join your table to that result on those two values this will limit the records that get returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With