Besides...the data you posted does not reflect the results you posted.

You will need to: a) Provide a working test case with create table/insert statements and b) Provide the proper rules to generate the output you expect.