I have an SQL table with duplicate records on FacilityID. FacilityKey is unique. I need to select rows that have duplicates on FacilityID but I only want to show one record for each and I want to choose the one with the most recent (highest) FacilityKey. Can anybody help me figure out how to write my query? I've tried everything I could think of and searched the internet for something similar to no avail. All I can find are examples of identifying the duplicate records.
Something like this should work:
select FacilityID, max(FacilityKey)
from Facilities
group by FacilityID
having count(FacilityID)>1
And then if you want to get all of the fields, something like this:
select *
from facilities
inner join (
select FacilityID, max(FacilityKey) as maxkey
from Facilities
group by FacilityID
having count(FacilityID)>1
) t on t.FacilityID = facilities.FacilityID and t.maxkey=facilities.FacilityKey
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With