I hope this solves your problem. I have used Pivot function to transform the data the way it was required. let me know if this one helps. I will explain this in detail.
Thanks and Regards,
Thanks Ashin. This is great. But that did not answer my question in how to count the number of columns as illustrated above?