--모든 필드값이 중복된 행 삭제

if OBJECT_ID('tempdb..#tmp') is not null

drop table #tmp 

GO 

select distinct * into #tmp from tblDupAll where col1 = 1 

GO 

delete tblDupAll where col1 = 1 

GO 

insert into tblDupAll select * from #tmp


--특정 필드값만 중복된 행 삭제 방법1

--중복필드 col1

declare @max integer,@id integer 

declare cur_rows cursor local for select col1,count(*) from 

tblDupCol group by col1 having count(*) > 1

open cur_rows 

fetch cur_rows into @id,@max 

while @@fetch_status=0 

begin 

select @max = @max -1 

set rowcount @max 

delete from tblDupCol where col1 = @id 

fetch cur_rows into @id,@max 

end 

close cur_rows 

set rowcount 0 


--특정 필드값만 중복된 행 삭제 방법2

--중복필드 col1

--col2값이 제일 큰 행을 남긴다

delete T1

from (

    select

        col1

    ,   col2

    ,   row_number() over(partition by col1 order by col1, col2 desc) as X

    from tblDupCol

) T1

where T1.X>1


--특정 필드값만 중복된 행 삭제 방법3

--중복필드 col2, col3

--col1값이 제일 작은 행을 남긴다

delete from tblDupCol 

where col1 not in (select min(col1) from duplicate_col group by col2,col3)



--중복행 조회

--중복필드 col1

select * from tblDupAll 

where col1 in (select col1 from tblDupAll group by col1 having count(col1) > 1) 


+ Recent posts