Here is a post that goes into detail about how the GROUP BY and FLATTEN operators work. I hope you find it helpful.