SQL 之 查詢操作重復記錄


  有時,我們的數據表中會存在一些冗余數據,這就要求我們查詢並操作這些冗余數據。

一、查詢表中重復記錄

  例如,查找重復記錄是根據單個字段(peopleId)來判斷 

SELECT * FROM Tpeople 
  WHERE peopleId IN ( SELECT peopleId FROM Tpeople GROUP BY peopleId HAVING COUNT(peopleId) > 1)

二、刪除表中多余的重復記錄

  例如,重復記錄是根據單個字段(peopleId)來判斷,只保留最先增加的記錄,下面是保留ID最小的記錄

DELETE FROM Tpeople 
  WHERE peopleName IN ( SELECT peopleName FROM Tpeople GROUP BY peopleName HAVING COUNT(peopleName)>1) 
    AND peopleId NOT IN ( SELECT MIN(peopleId) FROM Tpeople GROUP BY peopleName HAVING COUNT(peopleName)>1) 

三、查找表中多余的重復記錄(多個字段)
  A,DB2中可以如下查詢

SELECT * FROM vitae TA
 WHERE (TA.peopleId, TA.seq) IN ( SELECT peopleId,seq FROM vitae TB GROUP BY peopleId,seq HAVING COUNT(*) > 1)

  B,SQLServer如下查詢

SELECT * FROM vitae TA
 WHERE EXISTS ( SELECT * FROM vitae TB WHERE TB.peopleId=TA.peopleId AND TB.seq =TA.seq GROUP BY peopleId,seq HAVING COUNT(1) > 1)

四、刪除表中多余的重復記錄(多個字段),只留有最先插入的記錄

  A,DB2中可以如下刪除

DELETE FROM vitae TA
  WHERE (TA.peopleId,TA.seq) IN (SELECT peopleId,seq FROM vitae TB GROUP BY peopleId,seq HAVING COUNT(1) > 1) 
    AND rowid NOT IN ( SELECT MIN(rowid) FROM vitae TC GROUP BY peopleId,seq HAVING COUNT(1)>1)

  B,SQLServer中如下刪除

DELETE FROM vitae TA
  WHERE EXISTS ( SELECT * FROM vitae TB WHERE TB.peopleId=TA.peopleId AND TB.seq =TA.seq GROUP BY peopleId,seq HAVING COUNT(1) > 1)
    AND rowid NOT IN ( SELECT MIN(rowid) FROM vitae TC GROUP BY peopleId,seq HAVING COUNT(1)>1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM