我有两个表Add(父表)和AddXref(子表),并希望删除父表中的重复记录,并在Child表中更新。在AddXref表中,两个记录应该包含Add Table中的任何AddId.i尝试使用基本更新语句,但它没有工作。如何更新AddXref表?
我的尝试: 到目前为止,我已经编写了查询,但我仍然坚持下一步做什么
Update AddXref name
SET a.AddId=b.AddId
FROM AddXref a
INNER JOIN Add b ON a.AddId = b.AddId
WHERE b.AddId = ( Select Top 1 ax.Addid from Add ax
INNER JOIN Add ax1 on
ax.AddressMain = a.AddressMain and
ax.city = a.city and
ax.Country = a.Country and
ax.State = a.State and
ax.ZipCode = a.ZipCode);
| AddId | AddressMain | City | Country | State | ZipCode |
|--------|--------------|---------|---------|---------|------------|
| 8CA25D | 1234 Main St | Antioch | USA | Florida | 60002-9714 |
| 5T7YTR | 1234 Main St | Antioch | USA | Florida | 60002-9714 |
| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145 | 8CA25D | 7652ER | NULL |
| 435902 | 5T7YTR | NULL | NA1043 |
| AddXrefId | AddressId | IndividualId | InstitutionId |
|-----------|-----------|--------------|---------------|
| 822145 | 8CA25D | 7652ER | NULL |
| 435902 | 8CA25D | NULL | NA1043 | --Output either "8CA25D" or "5T7YTR" any one of it
答案 0 :(得分:1)
首先收集重复数据。
select AddressMain, City, Country, State, ZipCode, min(addId) as minID, Max(addId) as MAxID
INTO #tmpData
from add
group by AddressMain, City, Country, State, ZipCode
第二次更新子表
Update AddXref
SET a.AddId=b.MaxID
FROM AddXref a
INNER JOIN #tmpData b ON a.AddId = b.MinID -- you can use maxId too if you want.
第三个删除父母的重复记录。
DELETE FROM Add where AddId IN (Select MinID FROM #tmpData)
此代码未经过测试。