XSLT 2.0分组,求和,计数和条件

时间:2017-02-15 13:12:56

标签: xml xslt xslt-2.0

我有XSLT,它对输入进行分组,对当前组进行求和,并且只有在总和满足某个条件时才输出记录。 for-each-group工作正常,但我无法获得预告记录的准确记录。

这是一个示例输入:

<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>

这是一个示例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]))"/>

问题是顶部正确输出了第1本书。但是预告片对这两本书都进行了计算,我无法弄清楚如何调整总和来引用外部背景中的Book_ID。

1 个答案:

答案 0 :(得分:1)

你可以将for-each-group的结果输出存储在一个变量中,然后计算这些组,如果我明白你想要的那样:

    <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)"/>