[xsl] Grouping and Summing information

Subject: [xsl] Grouping and Summing information
From: "Anton Damhuis" <ADamhuis@xxxxxxxxxxxxxx>
Date: Wed, 2 Feb 2005 19:51:57 +0200

I need some assistance with grouping and summing information.
I have based this solution on info from  http://www.jenitennison.com/ using
the "Muenchian Method"

The problem is I will only know at run time:
a) what the program must Group By (G)
b) what the program must Sum by (S)

There can be an unlimited amount of <col>'s but each @id will be incrementd,
and each <col> will always have a @type of either 'G' (for 'Group By') or
'S' (for Sum).

Example of more columns: Later on there might be a column called "Area Code"
and it would need to be Grouped by that as well.

Sample XML:
      <col id='1' type='G'>Nummber Called</col>
      <col id='2' type='S'>Call Duration</col>
      <col id='3' type='S'>Call Cost</col>
      <col id='1' type='G'>0114520000</col>
      <col id='2' type='S'>100</col>
      <col id='3' type='S'>0.001</col>
      <col id='1' type='G'>0119744445</col>
      <col id='2' type='S'>111</col>
      <col id='3' type='S'>1.001</col>
      <col id='1' type='G'>0114520000</col>
      <col id='2' type='S'>200</col>
      <col id='3' type='S'>0.002</col>

My Transformation (XSL) looks like this:

  <xsl:key name="totalByGroup" match="data/values/cols" use="sort" />
    <xsl:for-each select="data/values/cols[count(. |
key('totalByGroup',sort)[1]) = 1]">
      <xsl:sort select="cols/sort" />
      <tr valign="top">
        <xsl:for-each select="col">
          <xsl:variable name="n" select="position()" />
            <xsl:if test="@type = 'G'">
              <xsl:value-of select="." />
            <xsl:if test="@type = 'S'">
              Error here=<xsl:value-of
select="sum(key('totalByGroup',sort)/col[($n)])" />!

What am I doing wrong that the sum does not compute?

If I do a <xsl:value-of select="sum(key('totalByGroup',sort)/col[2])" />
outside of the 'for-each select="col"' it works fine.

Current Thread