I have a table as follows:

This is the result of this selection:
SELECT ParentID, ID, [Default], IsOnTop, OrderBy
FROM [table]
WHERE ParentID IN (SELECT ParentID
FROM [table]
GROUP BY ParentID
HAVING SUM([Default]) <> 1)
ORDER BY ParentID
Now, what I want to do is: for each group, ParentIDset one of the lines as the default ( [Default] = 1), where the line is selected using this logic:
if the group has a line with IsOnTop = 1, then take this line, otherwise take the top 1 line, sorted by OrderBy.
I absolutely do not know how to do this in SQL, and I have more than 40 such groups, so I would like to ask you for help, preferably with some explanation of your request.
source
share