You haven't shown your key definition. However, keys are document-wide so to do grouping on subsets of a document you need to add information that makes each key unique within the document. In yor case, something like use="concat(@RelatedId, '~', ../../@Id) might do it. Of course you need to construct the concatenated key when you use the key() function as well.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference