Your question is Complex RDBMS Logic. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
Tell me about the most complex logic you have solved in an RDBMS and how you approached performance and correctness.