I have a table called PF_temo
that has the following structure:
- firstname
- middlename
- lastname
- DOB
- address
- city
- state
- phone
- validitydate
It has many rows that are identical, except for the validity date. For example:
steve,s,smith, 19710909,112 crazy st,miami,fl,3055551212,201609
steve,s,smith, 19710909,112 crazy st,miami,fl,3055551212,201002
steve,s,smith, 19710909,112 crazy st,miami,fl,3055551212,201706
steve,s,smith, 19710909,112 crazy st,miami,fl,3055551212,199812
I'd like to run a script that deletes all duplicates matched on everything but the last column (validitydate
) leaving just the below in the table, which is the most recent validitydate of 201706
:
steve,s,smith, 19710909,112 crazy st,miami,fl,3055551212,201706
This is what I have; though it throws an exception:
DELETE
FROM PF_temp
LEFT OUTER JOIN
(
SELECT Min(ValidityDate) as RowId
, firstname
, middlename
, lastname
, DOB
, address
, city
, state
, phone
FROM PF_temp
GROUP BY firstname
, middlename
, lastname
, DOB
, address
, city
, state
, phone
, validitydate
) as KeepRows
ON TableName.RowId = KeepRows.RowId
WHERE KeepRows.RowId IS NULL
It doesn't work and actually pops this error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'OUTER'.
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'as'.
Also, I'd like to run it in stages based on the last letter of the alphabet. So something like WHERE lastname like 'A%'
needs to be added somewhere.