简体   繁体   中英

MS Access FInd Duplicates

I have a MS Access table that had duplicate entries loaded to it. I used the query wizard and it returns both records. I need to return one record preferably with the id so I can use it to delete only the duplicate. Its been awhile since I used MS Access can this be done?

 UpdateTable
   ID
   PkgId
   CompName
   UpdDate   
   UpdQty

Data:

7212797   ADJ  E5780   9/27/2019 7;  
7213166   ADJ  E5780   9/27/2019 7; 
7212708   ADJ  E5912   9/27/2019 7;
7213167   ADJ  E5912   9/27/2019 7;

Consider the approach using a correlated subquery with an EXISTS condition:

SELECT id
FROM mytable t
WHERE EXISTS (
    SELECT 1 
    FROM mytable t1
    WHERE 
        t1.PkgId = t.PkgId 
        AND t1.CompName = t.CompName
        AND t1.UpdDate = t.UpdDate
        AND t1.UpdQty = t.UpdQty
        AND t1.id < t.id
)

This will return all id for which a duplicate exists (ie same pkgId/CompName/UpdDate/UpdQty ). The record with the lowest id is considered the original record and will not be returned by the query.

If you want to delete the records, there are multiple ways. I would go for a comparison on the id column:

delete from t
    where t.id < (select max(t2.id)
                  from t as t2
                  where t2.compname = t.compname and
                        t2.upddate = t.update and
                        t2.updqty = t.updqty and
                 );

That said, this will not work if any of the comparison columns are null . If id is a primary key, you can instead use:

delete from t
    where t.id not in (select max(t2.id)
                       from t t2
                       group by pkgid, compname, upddate
                      );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM