oracle刪除重資料方法

巡完南山巡南山發表於2019-01-21
<embed>

前期準備

建立測試表

create table salary( 

  staffid   int, 

  staff   varchar(15)  

);

模擬重複資料

insert into salary values(1,'a');

insert into salary values(2,'s');

insert into salary values(3,'ert');

insert into salary values(4,'d');

insert into salary values(5,'b');

insert into salary values(1,'a');

insert into salary values(2,'s');

insert into salary values(3,'ert');

insert into salary values(4,'d');

insert into salary values(5,'b');

insert into salary values(1,'a');

insert into salary values(2,'s');

insert into salary values(3,'ert');

insert into salary values(4,'d');

insert into salary values(5,'b');

insert into salary values(10,'aaaa');

insert into salary values(20,'sass');

insert into salary values(30,'erwt');

insert into salary values(40,'dsd');

insert into salary values(50,'bsdf');

insert into salary values(1,'oookkk');

實驗一:模擬單個欄位資料重複

select * from salary;

STAFFID STAFF

--------------- ---------------

              1 oookkk

              1 a

              2 s

              3 ert

              4 d

              5 b

              1 a

              2 s

              3 ert

              4 d

              5 b

              1 a

              2 s

              3 ert

              4 d

              5 b

             10 aaaa

             20 sass

             30 erwt

             40 dsd

             50 bsdf

21 rows selected

1.查出重複資料

方法一

SELECT *

FROM salary a

WHERE ((SELECT COUNT(*)

          FROM salary

          WHERE staffid = a.staffid) > 1)

ORDER BY staffid 

方法二

select *

  from salary

 where staffid in

(select staffid from salary group by staffid having count(staffid) > 1)

刪除重複資料,只保留1條,其餘全部刪除

方法一,透過rowid刪除

delete from salary

where staffid in (select staffid from salary group by staffid  having count(staffid) > 1)

and rowid not in (select min(rowid) from salary group by staffid having count(staffid )>1)

實驗二:模擬兩個個欄位資料重複

1.查詢重複記錄

方法一

select * from salary a

where (a.staffid,a.staff) in (select staffid,staff from salary group by staffid,staff having count(*) > 1)

方法二

SELECT *

FROM salary a

WHERE ((SELECT COUNT(*)

          FROM salary

          WHERE staffid = a.staffid and staff=a.staff) > 1)

ORDER BY staffid 

結果,共15條

STAFFID STAFF

1      a

1      a

1      a

2      s

2      s

2      s

3      ert

3      ert

3      ert

4      d

4      d

4      d

5      b

5      b

5      b

2.刪除重複資料,只保留1條,其餘全部刪除

delete from vitae a

where (a.peopleId,a.seq) in   (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)

and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

3.檢視刪除後結果

select * from salary;

結果

STAFFID STAFF

1      oookkk

1      a

2      s

3      ert

4      d

5      b

10    aaaa

20    sass

30    erwt

40    dsd

50    bsdf

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26964624/viewspace-2564339/,如需轉載,請註明出處,否則將追究法律責任。

相關文章