我有一个包含三个字段的地址历史记录表:EmpID
,Address
,AddrID
。
每次添加新地址时,我也会为该特定员工将地址ID(AddrID
)增加1。
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
如何获取每位员工的最新地址(最高地址ID)?理想情况下,我应该能够返回:
EmpID | AddrID | Address
-------------------------------
1 | 3 | 1111 First Ave
2 | 4 | 2222 Second St
3 | 2 | 3333 Third Lane
4 | 1 | 4444 Fourth Way
到目前为止,我要么返回太多结果(即每个Employee,每个AddrID 1,以及与这两个相关联的每个地址),或者结果太少(即每个具有AddrID 4的Employee - 只是Employee 2)。
我尝试过使用Distinct
,Group By
,Order By
,Having
和自我加入无效。
我错过了什么?
答案 0 :(得分:5)
您可以使用为每个empid获取MAX()
addrid的子查询:
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
内部查询将返回最大addrid
和empid
,然后您将表连接到这两个值的结果,这将限制返回的记录。
答案 1 :(得分:4)
以下内容应该有效:
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
中查看
答案 2 :(得分:0)
我可能会以不同的方式组织表格,但您可以使用子连接
执行某些操作 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