[Skip to Content]

XSLT Aggregation on Unique Items

Performing an aggregation for a set of nodes that match an expression is fairly simple. However, performing the same aggregation for only unique items introduces more complexity. For the sample XML snippet,

<applicant>

<address_details>

<court_judgements id="CJR" title="MRS" forename="R" surname=" JONES" value="42300" type="CJP" case_number="6XT01ZZZ"/>

<court_judgements id="CJR" title="MR" forename="A" surname=" JONES" value="42300" type="CJP" case_number="6XT01ZZZ"/>

</address_details>

<address_details>

<court_judgements id="CJV" title="" forename="ANDREW" surname="JONES" value="39600" type="CJ" case_number="QZ334ZZZ"/>

<court_judgements id="CJV" title="MR" forename="ANDREW" surname=" JONES" value="450500" type="CJ" case_number="XK105ZZZ"/>

</address_details>

<address_details>

<court_judgements id="CJR" title="MR" forename="A" surname=" JONES" value="42300" type="CJP" case_number="6XT01ZZZ"/>

</address_details>

</applicant>

Using the XSLT expression:

<xsl:variable name="totalvalue" select="sum(address_details/court_judgements/@value)" />

Gives a total value for all judgements of 671000. However, the first, second and last items have the case number and should only be counted once.

A useful example is provided at http://blogs.msdn.com/skaufman/archive/2006/03/13/550523.aspx. By excluding nodes where the case number matches a preceding-sibling the second item is not included. Changing this to preceding ensure that the second and last items are not included. Using this XSLT expression, give the correct total value for all judgements of 532400:

<xsl:variable name="totalvalue" select="sum(address_details/court_judgements[not(@case_number=preceding::court_judgements/@case_number)]/@value)" />

Comments

comments powered by Disqus