【问题标题】:Sum all instances of a particular node in a SQL Server XML column汇总 SQL Server XML 列中特定节点的所有实例
【发布时间】:2019-06-10 19:42:24
【问题描述】:

我有以下 xml 数据列:

<AccountingDetail>
    <DetailItems>
        <AccountingDetailItem>
            <Credit>25</Credit>
            <Debit>15100</Debit>
        </AccountingDetailItem>
        <AccountingDetailItem>
            <Credit>5</Credit>
            <Debit>150.66</Debit>
        </AccountingDetailItem>
    </DetailItems>
</AccountingDetail>

如何获得此列中所有贷方和借方的总和?实例的数量因行而异。

我希望 sum(debits) = 15250.66 & sum(credits) = 30

【问题讨论】:

    标签: sql-server xml xml-parsing


    【解决方案1】:

    您可以使用 CTE(通用表表达式)轻松完成此操作 - 类似这样(假设我们的 XML 数据存储在 @XmlData XML 变量中):

    -- define the CTE to extract the individual Credit and Debit values
    ;WITH RawXmlData (Credit, Debit) AS
    (
        SELECT
            Credit = ISNULL(XC.value('(Credit)[1]', 'decimal(16,4)'), 0.0),
            Debit = ISNULL(XC.value('(Debit)[1]', 'decimal(16,4)'), 0.0)
        FROM
            @XmlData.nodes('/AccountingDetail/DetailItems/AccountingDetailItem') XT(XC)
    )
    -- now select from that CTE and sum up the values
    SELECT
        SumCredit = SUM(Credit),
        SumDebit = SUM(Debit)
    FROM
        RawXmlData
    

    【讨论】:

      【解决方案2】:

      这可以在 XML/XQuery 中解决,它应该比创建派生集并在外部进行聚合更好:

      DECLARE @tbl TABLE(ID INT IDENTITY,YourXml XML);
      INSERT INTO @tbl VALUES
      (N'<AccountingDetail>
          <DetailItems>
              <AccountingDetailItem>
                  <Credit>25</Credit>
                  <Debit>15100</Debit>
              </AccountingDetailItem>
              <AccountingDetailItem>
                  <Credit>5</Credit>
                  <Debit>150.66</Debit>
              </AccountingDetailItem>
          </DetailItems>
      </AccountingDetail>')
      ,('<AccountingDetail>
          <DetailItems>
              <AccountingDetailItem>
                  <Credit>10</Credit>
                  <Debit>20</Debit>
              </AccountingDetailItem>
              <AccountingDetailItem>
                  <Credit>20</Credit>
                  <Debit>40</Debit>
              </AccountingDetailItem>
              <AccountingDetailItem>
                  <Credit>30</Credit>
                  <Debit>60</Debit>
              </AccountingDetailItem>
          </DetailItems>
      </AccountingDetail>');
      
      SELECT t.YourXml.value('sum(//Credit)','decimal(16,4)') AS SumCredit
            ,t.YourXml.value('sum(//Debit)','decimal(16,4)') AS SumDebit
      FROM @tbl t;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 2019-01-07
        相关资源
        最近更新 更多