简体   繁体   中英

SQL Select with multiple IDs

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.

The following should work:

SELECT * 
FROM   (SELECT empid, 
               Max(addrid) AS AddrID 
        FROM   t1 
        GROUP  BY empid) a 
       JOIN t1 b 
         ON b.empid = a.empid 
            AND b.addrid = a.addrid 

See it in action

I would probably organize the table differently, but you could do something with a sub-join

    select * from address_history 
    join 
    (select EmpID, max(AddrID) max_address from Address_History group by empId) as latest_addresses 
       on address_history.empid = latest_addresses 
       and address_history.addrId = latest_addresses.max_address 

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