我有一张包含4个列的表格,如下所示
var1 var2 var3 ran
a a a 1
b a a 2
c a a 3
d b b 4
e c c 1
这里基于var2和var3列中的值,它被认为是重复的。第4列是重复项的行号。我需要重新初始化非重复记录的行号(更新)。
预期结果将是(请注意d b b 4
成为d b b 1
):
var1 var2 var3 ran
a a a 1
b a a 2
c a a 3
d b b 1
e c c 1
答案 0 :(得分:2)
declare @T table
(
var1 char(1),
var2 char(1),
var3 char(1),
ran int
)
insert into @T values
('a', 'a', 'a', 1),
('b', 'a', 'a', 2),
('c', 'a', 'a', 3),
('d', 'b', 'b', 4),
('e', 'c', 'c', 1)
;with C as
(
select ran,
row_number() over(partition by var2, var3 order by var1) as rn
from @T
)
update C
set ran = rn
select *
from @T
结果:
var1 var2 var3 ran
---- ---- ---- -----------
a a a 1
b a a 2
c a a 3
d b b 1
e c c 1