I have some what of a challenging delete statement that I need help with. I’m trying to delete multiple duplicate records with multiple joins on the same table.
Here is an example of my data
versionid(PK) FileID(FK) Version DeleteDate DeleteIndicator
1 1 1 12/01/2003 1
2 1 1 12/02/2003 1
3 1 1 null 0
4 2 2 01/02/2004 1
5 2 2 01/03/2005 1
6 2 2 01/03/2006 1
The data I need to delete is all duplicate data matched by the FileId and the Version where DeleteDate is less than 04/01/2011 and the DeleteIndicator is = 1. But, I need to keep the highest VersionID out of the duplicate data that has the same FileId and Version
After the delete I would have this remaining:
versionid(PK) FileID(FK) Version DeleteDate DeleteIndicator
2 1 1 12/02/2003 1
3 1 1 null 0
6 2 2 01/03/2006 1
I have a select w/ multiple joins that would give me the above records. I just don’t know how to turn that into a delete statement. Here is my select statement.
SELECT t.VersionID ,
t.FileID ,
t.version ,
COUNT(*) ,
t.DeleteDate ,
t.DeleteIndicator
FROM tblFileVersions t
JOIN ( SELECT VersionID ,
FileID ,
MAX(VersionID) AS MaxVersion ,
DeleteDate ,
DeleteIndicator
FROM tblFileVersions
GROUP BY VersionID ,
FileID ,
DeleteDate ,
DeleteIndicator
) x ON t.FileID = x.FileID
WHERE t.DeleteDate < '2011/04/01'
AND t.DeleteIndicator = 1
AND t.VersionID < MaxVersion
GROUP BY t.VersionID ,
t.FileID ,
t.version ,
t.DeleteDate ,
t.DeleteIndicator ,
Version
HAVING COUNT(*) > 1
All I need to do is take what I have and make it a delete statement. Sorry if my text format is all screwed up this is the first time I have posted on here. Any help would be great thanks for your time.
Simpliest way to simple do that: