2016-12-05 64 views
0

我有2代表的表替換重複行 表1:團隊柱Teamid,teamName其具有一些重複 像在一個表中,並在具有外鍵參照第一表

Table 1 TeamID | TeamName 
------------------------------------- 
       1  | abc 
       2  | abc 

表2:其列ID UsedTeams,請求ID,teamdID(外鍵球隊(teamid))

Table 2 
ID |Requestid | teamID 
---|-----------|-------- 
1 | 1000  | 1 
2 | 1001  | 2 

我想是從球隊表中刪除重複的球隊喜歡在二手隊以teamid 2移除組,也該行有teamid等於到2肖ULD可以更新到teamid 1

+1

提示今天:唯一約束! – jarlh

回答

1

的CTE和OVER -clause有助於簡化任務:

WITH CTE AS 
(
    SELECT t.*, 
      RN = ROW_NUMBER() OVER (PARTITION BY TeamName ORDER BY TeamId), 
      MinTeamId = MIN(TeamId) OVER (PARTITION BY TeamName) 
    FROM Teams t 
) 
UPDATE ut SET ut.TeamId = CTE.MinTeamId 
FROM CTE INNER JOIN UsedTeams ut ON CTE.TeamId = ut.TeamId 
WHERE CTE.RN > 1 
相關問題