SQL to extract duplicates into a new table in Access

冷暖自知 提交于 2019-12-11 02:58:29

问题


Can I use SQL to extract data into a new table any duplicates within two existing tables?

The table below is a snapshot taken from an ERP system Pre my visit.

PRE
CO          Otp Los His Whs Fac
11889204    C20 22  66  1BA 1BA
11889132    C23 22  66  1BA 1BA
11888835    C20 23  66  1BA 1BA
11887689    C20 22  66  1BA 1BA
11884977    C20 22  22  1BA 1BA
11884624    C20 22  99  1BA 1BA

The table below is a snapshot taken after my visit.

POST
CO          Otp Los His Whs Fac
11889204    C20 22  66  1BA 1BA
11889132    C23 22  66  1BA 1BA
11888835    C20 23  66  1BA 1BA
11882804    C20 22  77  1BA 1BA
11882724    C20 22  77  1BA 1BA
11882521    C20 22  77  1BA 1BA
11882431    C20 22  22  1BA 1BA
11881410    C20 22  22  1BA 1BA
11881282    C20 22  22  1BA 1BA

Now what I want is the POST visit table to show only new records, and SQL to remove any records which are duplicated in the PRE and POST tables and create a new table and paste the duplicates there.

Now I am learning SQL but this is slightly out my depth. Anyone know if this is possible??


回答1:


This will insert matching rows from your PRE and POST tables into newtable:

INSERT INTO newtable (POSTCO,Otp, Los, His, Whs, Fac) 
SELECT POSTCO,Otp, Los, His, Whs, Fac FROM posttable
WHERE EXISTS 
(SELECT POSTCO,Otp, Los, His, Whs, Fac FROM pretable
    WHERE POSTCO = posttable.POSTCO AND Otp = posttable.Opt AND 
    Los = posttable.Los AND His = posttable.His AND 
    Whs = posttable.Whs AND Fac = posttable.Fac)

Then to remove the duplicate rows:

DELETE FROM posttable WHERE EXISTS
(SELECT POSTCO,Otp, Los, His, Whs, Fac 
    FROM pretable
    WHERE POSTCO = posttable.POSTCO AND Otp = posttable.Opt 
    AND Los = posttable.Los AND His = posttable.His 
    AND Whs = posttable.Whs AND Fac = posttable.Fac)


来源:https://stackoverflow.com/questions/19269026/sql-to-extract-duplicates-into-a-new-table-in-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!