这是我的第二次尝试。我正在尝试更新SQL表中的数据,其中有重复项来解决重复。
数据结构
DocNumbr SeQnumbr Dex_Row_Id
CRM025222 32768 1
CRM025222 32768 2
CRM025222 16384 3
期望的结果
DocNumbr SeQnumbr Dex_Row_Id
CRM025222 49152 1
CRM025222 32768 2
CRM025222 16384 3
对于每个副本,我需要通过Docnumbr + 16384将seqnumbr更新为重复项的seqnumbr的最大值.Dex_row_ID是主键并且是唯一的。
我的尝试
Begin
Declare @count as integer = (SELECT COUNT(*) AS DUPLICATES
FROM dbo.RM10101
GROUP BY DocNumbr, SeqNumbr
HAVING (COUNT(*) > 1))
Declare @counter as integer =1
While @Counter < @count
begin
Update RM10101 set SeqNumbr= (select MAX(dex_row_id) FROM RM10101 E2
WHERE E2.DocNumbr = RM10101.DocNumbr AND E2.SeqNumbr = RM10101.SeqNumbr) + (16384+)
WHERE dex_row_id < (select MAX(dex_row_id) FROM RM10101 E2
WHERE E2.DocNumbr = RM10101.DocNumbr AND E2.SeqNumbr = RM10101.SeqNumbr
)
SET @counter = @counter + 1
END
end
我已经尝试过上面的代码,但是用于添加到16384的值是所有行的最大seqnumbr,我需要它是重复集的最大值。我不是一个dba,但我正在被迫执行任务,而且我真的迷失了如何使连接或子查询正确。这是在SQL Server 2008中完成的。最初我被告知它是2000,所以如果有更好的方法使用cte或其他一些新方法,我会对它持开放态度。任何帮助将非常感激。 谢谢, 鲍勃
答案 0 :(得分:2)
-- Build Test Data
create table #test_table(
DocNumber varchar(255),
SeqNumber int,
Dex_Row_Id int
)
insert into #test_table
select 'CRM025222', 32768, 1 union all
select 'CRM025222', 32768, 2 union all
select 'CRM025222', 16384, 3
-- Solution: Start
;with cte as(
select
*,
rn = row_number() over(partition by DocNumber order by SeqNumber desc)
from #test_table
)
update cte
set SeqNumber = SeqNumber + 16384
where
rn = 1
-- Solution: End
select * from #test_table
-- Drop test data
drop table #test_table