刪除重複值

 

--1、查找表中多餘的重複記錄,重複記錄是根據單個字段(peopleId)來判斷  
select   *   from   people  
where   peopleId   in   (select     peopleId     from     people     group     by     peopleId     having     count(peopleId)   >   1)  
   
--2、刪除表中多餘的重複記錄,重複記錄是根據單個字段(peopleId)來判斷,只留有rowid最小的記錄  
delete   from   people    
where   peopleId     in   (select     peopleId     from   people     group     by     peopleId       having     count(peopleId)   >   1)  
and   rowid   not   in   (select   min(rowid)   from     people     group   by   peopleId     having   count(peopleId   )>1)  
   
--3、查找表中多餘的重複記錄(多個字段)    
select   *   from   vitae   a  
where   (a.peopleId,a.seq)   in     (select   peopleId,seq   from   vitae   group   by   peopleId,seq     having   count(*)   >   1)  
   
--4、刪除表中多餘的重複記錄(多個字段),只留有rowid最小的記錄  
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)  
   
--5、查找表中多餘的重複記錄(多個字段),不包含rowid最小的記錄  
select   *   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)


--經典嘗試   刪除重複值

declare @table table (id int,name nvarchar(10))
insert into @table select 1,'aa'
        union all  select 1,'aa'
        union all  select 2,'bb'
        union all  select 3,'bb'
        union all  select 4,'cc'
        union all  select 1,'aa'
        union all  select 4,'cc'

delete a
from (
    select id,name,rn = row_number() over (partition by id,name order by id) from  @table
) a where rn > 1

select * from @table

id          name
----------- ----------
1           aa
2           bb
3           bb
4           cc

(4 row(s) affected)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章