Вы можете попробовать следующий запрос, используя функции row_number()
, cte
и inner join
, как показано ниже.
Примечание: Если вы хотите обновить значения с дубликатом и оставить один из этих записей как и в этом случае, вам не нужно снова объединяться с таблицей.
create table SampleTable( col1 varchar(10)
, col2 varchar(10)
, col3 bit)
insert into SampleTable values
('abc', 'xyz', 0),
('abc', 'xyz', 1),
('abc', 'xyz', 0),
('abc', 'xyz', 0)
--Before update
select * from SampleTable
--Getting rows with duplicate
; with cte as (SELECT col1
, col2
, col3
, row_number() over (partition by col1, col2, col3 order by (select null)) as cnt
FROM SampleTable
)UPDATE t
set t.col1 = t.col1
, t.col2 = t.col2
, t.col3 = 1
from SampleTable t
inner join cte on t.col1 = cte.col1
and t.col2 = cte.col2 and t.col3 = cte.col3
and cnt > 1
--After update
select * from SampleTable
Здесь находится живое db <> fiddle демо.
Здесь другой способ использования exists
.
Второй подход
update t1
set t1.col1 = t1.col1
, t1.col2 = t1.col2
, t1.col3 = 1
from SampleTable t1
where exists (select 1
from SampleTable t2
where t1.col1 = t2.col1
and t1.col2 = t2.col2
and t1.col3 = t2.col3
group by col1, col2, col3
having count(*) > 1)