It'd be better if you provide some examples in excel of your data sample (fake data) and expected results.
There you can describe all possible cases, constraints etc...
It helps other people do not waste time for understanding of many-many-many rows of description text.
I've made an example according to your explanation, hope it helps you.
Test2.qvw 155.5 K