I have a table t_objectproperties in a MSSQL database like follows
PropertyID | ObjectID | Property |
---|---|---|
ID1 | Object1 | Property1 |
ID2 | Object1 | Property1 |
ID3 | Object1 | Property1 |
ID4 | Object2 | Property1 |
I would like to delete all duplicates of a property within the same object. So the rows (ID2, Object1, Property1 AND ID3, Object1, Property1) should be deleted while the rows (ID1, Object1, Property1 AND ID4, Object2, Property1) must not be deleted. I always want to keep the lowest PropertyID of the multiple Properties within the same object.
Until now I tried the following code but didn't get a satisfying result. (I tried with SELECT instead of DELETE, in order to first confirm that my statement is correct)
WITH CTE AS(
SELECT t_objectproperties.Property, t_objectproperties.ObjectID, t_objectproperties.PropertyID,
RN = ROW_NUMBER()OVER(PARTITION BY t_objectproperties.Property ORDER BY t_objectproperties.PropertyID ASC)
FROM t_objectproperties
)
SELECT * FROM CTE WHERE RN > 1
If I partition by ObjectID the result is different but still not what I'm looking for.
Further I tried extracting the correct format of my data with the following statement.
SELECT t_objectproperties.ObjectID, t_objectproperties.Property, count(*)
From t_objectproperties
Group by t_objectproperties.ObjectID, t_objectproperties.Property
While the groupy by extracts the data correctly, I can't use that statement to delete my rows. Somehow I need to combine the two statements.
I've found a lot of answers here and on google, but they never wanted to group/partition by 3 columns and then delete it.
How can I extract/delete the respective data?