Reputation: 77
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??
Upvotes: 2
Views: 174
Reputation: 2292
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)
Upvotes: 2