The DDL and sample data were helpful. You could use the IFCode tags to avoid having a very large post and keep formatting but that's just style. 🙂
I got lost on the expected results, but maybe that was just me. I might have get confused because I couldn't relate the title with the description.