Anzer Muhammad
An interesting and challenging question.
However it is more likely to be answered if you follow the examples of how to post a question (refer to the link in my signature block). Please expand you question to include table definitions (Create Table ...) as well as some sample data for those tables. Also include what you expect the output to be.