티베로(Tibero) 오라클(Oracle)

[오라클] having, 중복건중 1건만 남기고 싶을때. rowid를 이용한 중복건 삭제

xemaker 2018. 10. 10. 10:36

우선 오라클 having 에 관해 살펴보면


select emp

from EMP

group by emp

having count(*) > 1

;


이러면 emp가 2건 이상인것 만 출력된다.


이것에 이어서 중복건 중 1건만 남기고 싶을 때가 있다.


ROW마다 있는 ROWID를 이용해 중복건 삭제하는 방법을 살펴보자.


select emp

,count(*) over (partition by emp) as cnt

from 테이블명


하면 전체 ROW에 대한 중복 갯수가 출력된다.


select a.* from(

select emp

,count(*) over (partition by emp) as cnt

,rowid

,row_number() over(partition by emp order by emp desc) rn

from 테이블명

order by cnt desc, rn asc

) a

where rn >1

;


하면 중복건 중 2건 이상인것들에 대한 rowid가 출력된다.

그럼 이 건들만 삭제하면 중복건중 1개만 남는다.

select 대신 delete로 바꿔준다.


delete from

테이블명

where rowid in(

select rowid from

(

select emp

,count(*) over (partition by emp) as cnt

,rowid

,row_number() over(partition by emp order by emp desc) rn

from 테이블명

order by cnt desc, rn asc

) a

where rn >1

)

;