XSLT 2.0 Grouping, Summing, Counting and Conditions

流过昼夜 提交于 2019-12-13 08:10:27

问题


I have XSLT that is grouping the input, summing the current-group, and only outputting a record if the sum meets a certain condition. The for-each-group works fine, but I can't get an accurate record count for a trailer record.

Here's a sample input:

<Book_Data>
  <Book_Entry>
    <Book>
      <Book_ID>1</Book_ID>
      <Book_Name>Test1</Book_Name>
    </Book>
    <Sales>
      <Quantity>2</Quantity>
    </Sales>
  <Book_Entry>
  <Book_Entry>
    <Book>
      <Book_ID>1</Book_ID>
      <Book_Name>Test1</Book_Name>
    </Book>
    <Sales>
      <Quantity>3</Quantity>
    </Sales>
  <Book_Entry>
  <Book_Entry>
    <Book>
      <Book_ID>2</Book_ID>
      <Book_Name>Test2</Book_Name>
    </Book>
    <Sales>
      <Quantity>3</Quantity>
    </Sales>
  <Book_Entry>
  <Book_Entry>
    <Book>
      <Book_ID>2</Book_ID>
      <Book_Name>Test2</Book_Name>
    </Book>
    <Sales>
      <Quantity>-3</Quantity>
    </Sales>
  <Book_Entry>
</Book_Data>

And here is a sample XSLT (2.0):

<xsl:for-each-group select="Book_Data/Book_Entry" group-by="Book/Book_ID">
        <xsl:if test="sum(current-group()/Sales/Quantity) != 0">
            <xsl:value-of select="Book/Book_ID"/>
            <xsl:value-of select="Book/Book_Name"/>
        </xsl:if>
</xsl:for-each-group>

<xsl:value-of select="count(distinct-values(Book_Data/Book_Entry/Book/Book_ID[sum(../../Sales/Quantity) != 0]))"/>

The problem is the top section correctly outputs only book 1. But the trailer counts both books, and I can't figure out how to condition the sum to reference a Book_ID in the outer context.


回答1:


You could store the resulting output of the for-each-group in a variable and then count the groups, if I understand what you want:

    <xsl:variable name="groups" as="xs:string*">
        <xsl:for-each-group select="Book_Data/Book_Entry" group-by="Book/Book_ID">
            <xsl:if test="sum(current-group()/Sales/Quantity) != 0">
                <xsl:sequence select="current-grouping-key()"/>
            </xsl:if>
        </xsl:for-each-group>          
    </xsl:variable>

    <xsl:value-of select="$groups"/>
    <xsl:value-of select="count($groups)"/>


来源:https://stackoverflow.com/questions/42250394/xslt-2-0-grouping-summing-counting-and-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!