sql 去除重複記錄


排除左右交叉相同的記錄:
create table Ta as(
select 'a' f1,'b' f2 from dual union all
select 'b' f1,'a' f2 from dual union all
select 'q' f1,'p' f2 from dual union all
select 'm' f1,'n' f2 from dual union all
select 'n' f1,'m' f2 from dual );

①:
select * from Ta
minus  --集合相減
select t1.f1,t1.f2 from ta t1,ta t2
where t1.f1=t2.f2 and t1.f2=t2.f1 and t1.f1>t2.f1;

選出相同的結果,與原表連接 exists
select * from Ta 
where not exists
(select 1 from
(select t1.f1,t1.f2 from ta t1,ta t2
where t1.f1=t2.f2 and t1.f2=t2.f1 and t1.f1>t2.f1 )b
where b.f1=Ta.f1) 
;


如果左右相同的話,ascii碼相加的和是一樣的,所以按ascii相加的和分組排序 a+z與 b+y是相等的 會出錯
select f1,f2 from (
select f1,f2, row_number() over(partition by ascii(f1)+ascii(f2)  order by ascii(f1)+ascii(f2)) rn from Ta)t1
where rn=1
;


去除重複記錄
①無id 直接distinct
②1列id,一列數據:
select * from t4;
id f1
1 a
2 a
3 q
4 m
5 n
select id,f1 from (
select id,f1,
row_number() over(partition by f1 order by id) rn from t4)
where rn=1
order by id;


③1列id,多列數據:


Create table t4 as
(
select 1 id,'a' f1,'b' f2 from dual union all
select 2,'a' f1,'b' f2 from dual union all
select 3,'q' f1,'p' f2 from dual union all
select 4,'m' f1,'n' f2 from dual union all
select 5,'n' f1,'m' f2 from dual );


select id,f1,f2 from(
select id,f1,f2,row_number() over(partition by f1,f2 order by f1,f2) rn from t4)
where rn=1
order by id;


刪除:
delete from t4 where id in(
select id from (
select id,f1,f2,row_number() over(partition by f1,f2 order by f1,f2) rn from t4
)
where rn>1
)
發佈了34 篇原創文章 · 獲贊 16 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章