【Oracle_SQL】查詢/刪除重複的資料(單個欄位和多個欄位條件)
阿新 • • 發佈:2019-01-23
oracle查詢/刪除重複的資料(單個欄位和多個欄位條件)
單個欄位:
--查詢重複的全部資料(單個欄位)
思路:
1.根據欄位tid分組,數量大於1的表示tid欄位有重複的資料;
2.根據1查詢出來的tid資料為條件,再查詢全部重複的資料。
SQL:
select t.* from test1108 t
where t.tid in (select tid from test1108 group by tid having count(tid) > 1);
--刪除多餘的重複資料(單個欄位),重複的資料保留rowid最小的行
思路:
1.根據欄位tid分組,數量大於1的表示有重複資料;
2.因表中每行都有一個偽列rowid,查找出重複資料中最小的rowid;
3.根據1、2的並行條件重複的資料,但保留重複資料中rowid最小的值。
SQL:
delete from test1108 t
where t.tid in (select tid from test1108 group by tid having count(tid) > 1)
and rowid not in (select min(rowid) from test1108 group by tid having count(tid) >1);
多個欄位:
--查詢重複的全部資料(多個欄位)
思路:
1.根據欄位tid,tname分組,數量大於1的表示欄位tid,tname有重複的資料;
2.根據1查詢出來的tid,tname資料為條件,再查詢全部重複的資料。
SQL:
select * from test112101 t
where (t.tid,t.tname) in (
select tid,tname
from test112101 t1
group by t1.tid,t1.tname having count(*) >1
);
--刪除多餘的重複資料(多個欄位),重複的資料保留rowid最小的行
思路:
1.根據欄位tid,tname分組,數量大於1的表示有重複資料;
2.因表中每行都有一個偽列rowid,查找出重複資料中最小的rowid;
3.根據1、2的並行條件重複的資料,但保留重複資料中rowid最小的值。
SQL:
delete from test112101 t
where (t.tid,t.tname) in (
select tid,tname
from test112101 t1
group by t1.tid,t1.tname having count(*) >1
)
and rowid not in(
select min(rowid) from test112101
group by tid,tname having count(1)> 1);