我有一个要在其中更新两列的表。下面是示例:
实际表格:
Team | PLAYERNUM| NAME
--------+----------+--------
A | 1 | ONE |
A | 2 | TWO |
A | 3 | THREE|
B | 1 | FOUR |
B | 2 | FIVE |
B | 3 | SIX |
预期结果:
Team |PLAYERNUM | NAME
--------+----------+--------
A | 1 | ONE |
A | 2 | TWO |
A | 3 | THREE|
A | 4 | FOUR |
A | 5 | FIVE |
A | 6 | SIX |
在“ Team”和“ PLAYERNUM”列上启用了唯一约束。现在,我想将“团队”作为“ B”的所有行更新为“ A”。我收到一个唯一的违反约束的错误,因为“ PLAYERNUM”是唯一的。有关如何将B组和PLAYERNUM更新为4 5 6的任何线索。
答案 0 :(得分:0)
您可以使用common-table-expression
和row_number()
窗口分析功能来执行更新操作:
update tab t
set playernum = (
with cte as (
select t.*, row_number() over (order by Team,playernum) as rn
from tab t
)
select rn
from cte
where cte.team = t.team and cte.playernum = t.playernum
), team = 'A';
如果仅将列团队更新为team ='A',则会收到主键约束冲突错误(在演示中尝试),但是上述样式不会产生错误。 >