ar1991
ar1991

Reputation: 25

XSLT - Grouping and Sum Issue

I want to Group the values by Type and get sum of grosspay of similar Type in single row using below XML. I have provided sample data of XML and expected output that i am trying to achieve.

<---XML Data---->

<Payroll_Data>
<EmpId>1000</EmpId>
<FirstName>Mark</FirstName>
<LastName>Henry</LastName>
<Salary>
    <Type>B</Type>   
    <GrossPay>1000.50</GrossPay>
</Salary>
<Salary>
    <Type>B</Type>   
    <GrossPay>847.50</GrossPay>
</Salary>
<Salary>
    <Type>X</Type>   
    <GrossPay>820</GrossPay>
</Salary>
</Payroll_Data>
<Payroll_Data>
<EmpId>1001</EmpId>
<FirstName>John</FirstName>
<LastName>Diggle</LastName>
<Salary>
    <Type>B</Type>   
    <GrossPay>800.98</GrossPay>
</Salary>
<Salary>
    <Type>X</Type>   
    <GrossPay>630.50</GrossPay>
</Salary>
<Salary>
    <Type>X</Type>   
    <GrossPay>600.50</GrossPay>
</Salary>

</Payroll_Data>

<----Expected Result---->

EmpId   FirstName   LastName    Type    GrossPay    Sum of Grosspay by Type
1000    Mark        Henry       B       1000.50     1847.99
1000    Mark        Henry       B       847.49            
1000    Mark        Henry       X       820         820
1001    John        Diggle      B       800.98      800.98
1001    John        Diggle      X       630.50      1231
1001    John        Diggle      X       600.50      

Upvotes: 0

Views: 172

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

Like @ar1991 says, but I think it's:

 <xsl:template match="Payroll_Data">
      <xsl:for-each-group select="Salary" group-by="Type">
        <xsl:for-each select="current-group()">
           <xsl:value-of select="../(EmpId, FirstName, LastName), Type, GrossPay, 
              if (position()=1) then sum(current-group()/GrossPay) else ''" 
                         separator="&#9;"/>
          <xsl:text>&#10;</xsl:text>
        </xsl:for-each>
      </xsl:for-each-group>
  </xsl:template>

Upvotes: 1

ar1991
ar1991

Reputation: 25

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output method="text"/>
  <xsl:variable name="comma" select="','"/>

  <xsl:template match="/">
     <xsl:apply-templates select="//Payroll_Data"/>
  </xsl:template>

  <xsl:template match="Payroll_Data">
      <xsl:for-each-group select="Salary" group-by="Type">
      <xsl:value-of select="../(EmpId, FirstName, LastName), Type, GrossPay, sum(current-group()/GrossPay)" separator="&#9;"/>
      <xsl:text>&#10;</xsl:text>
      </xsl:for-each-group>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 0

Related Questions