Your question is "Need query for problem".
Would you mind sharing the logic you came up with to solve the problem? We might be able to help you "translate" it into T-SQL, if possible.
As others already stated, the problem itself is rather complex.
What exactly are you looking for?
A few hints how to tackle the problem -> already available
Links to a few SQL code samples how to solve it -> already provided
A coded solution that specifically solve your issue -> not available. Either use the hints you have so far or hire someone to solve it for you.
You might want to rethink the way you post.
Something along "Nope, not what I want. Next one!" doesn't help at all...