简体   繁体   中英

Access SQL append latest records to historical table

I have this access SQL append query where I have a Primary key set to now allow duplicates in the destination table. I'm confused if I am accomplishing the right thing here with the WHERE condition.

I am trying to only screen the newest records from the source table 'tbl_IMEI_MASTER' and only append(add) the records that do not have a match on the key in the destination table (same identifier as the source table). I think it's working but I did get a message that 72 rows (which is the total that were new and unique for the addition to the source table based on most recent date) were being updated in the destination table when only 14 of them should have been updated/added. Only 14 should have been identified as not having the same unique key.

INSERT INTO leads_historical (Customer, LeadNumber, ImportDate)
SELECT DISTINCT tbl_IMEI_MASTER.Customer, tbl_IMEI_MASTER.LeadNumber, tbl_IMEI_MASTER.ImportDate
FROM tbl_IMEI_MASTER
WHERE tbl_IMEI_MASTER.ImportDate = (SELECT MAX(tbl_IMEI_MASTER.ImportDate) FROM tbl_IMEI_MASTER);

I got it -

Using just select to break it down further I drilled down to the desired result.

SELECT DISTINCT tbl_IMEI_MASTER.Customer, tbl_IMEI_MASTER.LeadNumber, tbl_IMEI_MASTER.ImportDate
FROM tbl_IMEI_MASTER
WHERE tbl_IMEI_MASTER.ImportDate=(SELECT MAX(tbl_IMEI_MASTER.ImportDate) FROM tbl_IMEI_MASTER) AND NOT EXISTS (SELECT leads_historical.Customer FROM leads_historical WHERE leads_historical.Customer = tbl_IMEI_MASTER.Customer);

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