WITH CTE as (
   SELECT id,ROW_NUMBER() OVER (PARTITION BY deviceId, stateKey ORDER BY updatedutc DESC) AS RowNumber
    FROM [DeviceStates]
)

delete FROM [DeviceStates] 
WHERE id IN (SELECT id FROM CTE WHERE RowNumber > 1);
