Welcome to the forum Henry.
As this is quite an involved problem, may I suggest that you check out the link in my signature and then post some consumable DDL and DML to set up test tables, data & show sample results.
If you take the time to do this, I am sure that someone will help you.
If you haven't even tried to resolve your issue, please don't expect the hard-working volunteers here to waste their time providing links to answers which you could easily have found yourself.