The answer to grouping problems depends strongly on whether you are using XSLT 1.0 or 2.0.
For XSLT 1.0, use Muenchian grouping. Any good XSLT book will cover it. It's conceptually tricky when you first encounter it, but once you've learnt the coding pattern, it's fairly straightforward.
For XSLT 2.0, use the xsl:for-each-group instruction.
Author, XSLT 2.0 and XPath 2.0 Programmer\'s Reference